Compare commits

...

85 Commits

Author SHA1 Message Date
Jonas Bark
b875489ad3 more logging 2025-04-02 18:29:41 +02:00
Jonas Bark
ece3f3822f increase connection timeout, logging 2025-04-02 13:34:40 +02:00
Jonas Bark
0780cdc80b increase connection timeout, logging 2025-04-02 13:30:25 +02:00
Jonas Bark
1c0e027abb Android: make sure the touch reassignment page is fullscreen 2025-04-02 12:20:56 +02:00
Jonas Bark
0dcb666bbd update changelog 2025-04-01 21:21:58 +02:00
Jonas Bark
00ebca7a01 Merge branch 'windows' 2025-04-01 21:20:25 +02:00
Jonas Bark
f9c8820303 version++ 2025-04-01 21:20:20 +02:00
Jonas Bark
3d414edda9 Zwift Ride: cleanup, fix button 2025-04-01 21:17:46 +02:00
Jonas Bark
0e3f6f1d5e Windows: implement keybd_event 2025-04-01 19:54:41 +02:00
Jonas Bark
c4b0ef38c0 Zwift Ride: only connect to the left controller 2025-04-01 19:38:52 +02:00
Jonas Bark
2e800bb2de add hint to install runtime libraries for windows 2025-04-01 11:48:38 +02:00
Jonas Bark
505b970497 show the connected device type if the bluetooth name is null 2025-04-01 09:43:08 +02:00
Jonas Bark
986bfd481c show the connected device type if the bluetooth name is null 2025-04-01 09:42:40 +02:00
Jonas Bark
ab8d480a01 change SendInput to use keybd_event instead 2025-04-01 09:39:41 +02:00
Jonas Bark
7e19b76403 integrate keypress_simulator to make changes 2025-04-01 09:25:05 +02:00
Jonas Bark
cbc2f103ac run connection sequentially - may fix issues on Windows 2025-04-01 09:21:31 +02:00
Jonas Bark
6a7922cf17 version++ 2025-03-31 21:00:37 +02:00
Jonas Bark
8e23de2718 version update check => internet permission is required 2025-03-31 20:58:27 +02:00
Jonas Bark
11aec5fba1 Zwift Ride: add buttonPowerDown to shift gears
Zwift Play: Fix buttonShift assignment
Android: fix Media next button
2025-03-31 20:20:47 +02:00
Jonas Bark
c98f213e2e add some comments 2025-03-30 21:34:29 +02:00
Jonas Bark
8c11cfcad6 remove location requirement again 2025-03-30 21:21:31 +02:00
Jonas Bark
5fe88ffc6a version++ 2025-03-30 21:18:38 +02:00
Jonas Bark
7a8c7a4ee1 fix #6 for real this time 2025-03-30 21:18:18 +02:00
Jonas Bark
3343325195 adjust reinstating saved keymaps 2025-03-30 20:06:44 +02:00
Jonas Bark
edda16dc06 adjust reinstating saved keymaps 2025-03-30 19:30:34 +02:00
Jonas Bark
7a3d120123 Keyboard: no point in catching modifiers 2025-03-30 18:58:38 +02:00
Jonas Bark
92419c9182 potential fix for #6 2025-03-30 18:44:55 +02:00
Jonas Bark
68bb5bf371 Zwift Ride: adjust on off button detection 2025-03-30 18:30:15 +02:00
Jonas Bark
b0d8bfcadd potential fix for #7 2025-03-30 18:29:01 +02:00
Jonas Bark
a58ad1daf6 potential fix for Bluetooth device detection 2025-03-30 16:53:34 +02:00
Jonas Bark
657c6056c4 potential fix for Bluetooth device detection 2025-03-30 16:08:03 +02:00
Jonas Bark
84daba8902 potential fix for Bluetooth device detection 2025-03-30 16:03:01 +02:00
Jonas Bark
3e37f8a269 update readme 2025-03-30 15:17:52 +02:00
Jonas Bark
28d178c4be update changelog + version 2025-03-30 15:04:00 +02:00
Jonas Bark
f560cd5930 don't call getSystemDevices on Web 2025-03-30 15:02:04 +02:00
Jonas Bark
dbf24c6cd3 fix touch placement coordinate systems (closes #4) 2025-03-30 15:00:24 +02:00
Jonas Bark
0a4989ca47 fix touch placement coordinate systems (closes #4) 2025-03-30 14:59:42 +02:00
Jonas Bark
507dbf5d0f cleanup code 2025-03-30 14:40:08 +02:00
Jonas Bark
536f36f4e7 update Zwift Ride decoding based on Feedback from @JayyajGH
fixes #3
2025-03-30 14:30:38 +02:00
Jonas Bark
c523ba2287 Android: allow user to adjust touch placements 2025-03-30 14:26:51 +02:00
Jonas Bark
a3f1cbb3b1 reconnect to existing BLE connection, also fallback to name only if manufacturerData isn't available 2025-03-30 14:09:41 +02:00
Jonas Bark
561bb2f0f4 allow adding custom keymap and store it 2025-03-30 13:36:40 +02:00
Jonas Bark
dbbd1b5f2c another potential keyboard fix, Zwift Play adjustment 2025-03-29 21:15:43 +01:00
Jonas Bark
7f6ec2f732 revert keyboard change 2025-03-29 19:48:51 +01:00
Jonas Bark
e8649203cf Zwift Ride: more work on https://github.com/jonasbark/swiftcontrol/issues/3#issuecomment-2763633261 2025-03-29 17:42:08 +01:00
Jonas Bark
765b0c3d6d Zwift Ride: more work on https://github.com/jonasbark/swiftcontrol/issues/3#issuecomment-2763633261 2025-03-29 17:38:41 +01:00
Jonas Bark
248c40731c potential fix for https://github.com/jonasbark/swiftcontrol/issues/1#issuecomment-2763382744 2025-03-29 15:12:10 +01:00
Jonas Bark
cde01a4863 fix build 2025-03-29 15:07:01 +01:00
Jonas Bark
1ee8a0188b try to resolve https://github.com/jonasbark/swiftcontrol/issues/3#issuecomment-2763361122 2025-03-29 14:54:16 +01:00
Jonas Bark
32e8fc9bf5 try to resolve https://github.com/jonasbark/swiftcontrol/issues/3#issuecomment-2763361122 2025-03-29 14:37:07 +01:00
Jonas Bark
3c87d895c5 fix missing permissions for Android 2025-03-29 14:34:39 +01:00
Jonas Bark
82dd8a9b48 sign Android APK 2025-03-29 14:16:17 +01:00
Jonas Bark
0996506fd1 attempt to fix #3 2025-03-29 13:49:22 +01:00
Jonas Bark
3ee38ee1e2 update changelog 2025-03-29 13:07:18 +01:00
Jonas Bark
cf9401d81c resolve https://github.com/jonasbark/swiftcontrol/issues/2 2025-03-29 12:53:27 +01:00
Jonas Bark
dbed5cc247 refactor to use universal_ble 2025-03-29 12:26:47 +01:00
Jonas Bark
625a77fd74 Merge branch 'universal_ble' 2025-03-29 11:51:28 +01:00
Jonas Bark
f7856cd71a fix build, add zwift_ride.html for debugging 2025-03-29 11:04:19 +01:00
Jonas Bark
3e56c32376 attempt to fix windows ble issue 2025-03-29 10:54:26 +01:00
Jonas Bark
56ecad07cd remove dependency again 2025-03-29 10:28:00 +01:00
Jonas Bark
de8ef5f10b attempt to fix windows ble issue 2025-03-29 02:02:32 +01:00
Jonas Bark
022df97b89 fix indicate on macOS 2025-03-28 23:15:56 +01:00
Jonas Bark
662480ef4c integrate universal_ble 2025-03-28 23:14:06 +01:00
Jonas Bark
446743c4cf windows: fix bad imports, naming conflict 2025-03-28 20:57:11 +01:00
Jonas Bark
ebb670b328 windows: find by name only 2025-03-28 20:35:08 +01:00
Jonas Bark
74d253cdc3 reset build.yml 2025-03-28 18:28:58 +01:00
Jonas Bark
a368b4a271 hint to downloads 2025-03-28 18:28:27 +01:00
Jonas Bark
16a71f4c65 rename APK 2025-03-28 18:20:04 +01:00
Jonas Bark
3790bca2e7 zip that directory 2025-03-28 17:44:36 +01:00
Jonas Bark
34fd830859 zip that directory 2025-03-28 17:44:24 +01:00
Jonas Bark
9c0be2fe7a zip that directory 2025-03-28 17:43:18 +01:00
Jonas Bark
e5f7f593b2 build windows 2025-03-28 17:27:20 +01:00
Jonas Bark
b189a9a435 try to sign macOS app 2025-03-28 17:08:15 +01:00
Jonas Bark
479172f34d try to sign macOS app 2025-03-28 17:02:53 +01:00
Jonas Bark
9eb2a43cd2 try to sign macOS app 2025-03-28 16:43:47 +01:00
Jonas Bark
1110df67d9 try to notarize macOS app 2025-03-28 16:16:49 +01:00
Jonas Bark
9a88313199 control media (Android only for now), add menu 2025-03-28 15:24:25 +01:00
jonasbark
f41560e285 Update README.md 2025-03-28 14:45:37 +01:00
Jonas Bark
4d37a1aca1 Merge remote-tracking branch 'origin/main' 2025-03-28 14:34:05 +01:00
Jonas Bark
01fbb0e663 github actions 2025-03-28 14:33:57 +01:00
jonasbark
91e4bd7475 Create FUNDING.yml 2025-03-28 14:17:28 +01:00
Jonas Bark
3a111499f1 github actions 2025-03-28 13:48:01 +01:00
Jonas Bark
4548981d1b github actions 2025-03-28 13:45:56 +01:00
Jonas Bark
d026d26ae9 github actions 2025-03-28 13:05:13 +01:00
Jonas Bark
cca7cd7962 github actions 2025-03-28 13:04:39 +01:00
127 changed files with 3471 additions and 2772 deletions

3
.github/FUNDING.yml vendored Normal file
View File

@@ -0,0 +1,3 @@
github: [jonasbark]
open_collective: jonas-bark1
custom: ["https://paypal.me/boni"]

View File

@@ -10,11 +10,40 @@ jobs:
name: Build & Release
runs-on: macos-latest
permissions:
id-token: write
pages: write
contents: write
steps:
#1 Checkout Repository
- name: Checkout Repository
uses: actions/checkout@v3
- name: Install certificates
env:
DEVELOPER_ID_APPLICATION_P12_BASE64_MAC: ${{ secrets.DEVELOPER_ID_APPLICATION_P12_BASE64_MAC }}
P12_PASSWORD: ${{ secrets.P12_PASSWORD }}
KEYCHAIN_PASSWORD: ${{ secrets.KEYCHAIN_PASSWORD }}
run: |
# create variables
DEVELOPER_ID_APPLICATION_CERTIFICATE_PATH=$RUNNER_TEMP/build_developerID_application_certificate.p12
KEYCHAIN_PATH=$RUNNER_TEMP/pg-signing.keychain-db
# import certificate and provisioning profile from secrets
echo -n "$DEVELOPER_ID_APPLICATION_P12_BASE64_MAC" | base64 --decode --output $DEVELOPER_ID_APPLICATION_CERTIFICATE_PATH
# create temporary keychain
security create-keychain -p "$KEYCHAIN_PASSWORD" $KEYCHAIN_PATH
# security default-keychain -s $KEYCHAIN_PATH
security set-keychain-settings -lut 21600 $KEYCHAIN_PATH
security unlock-keychain -p "$KEYCHAIN_PASSWORD" $KEYCHAIN_PATH
# import certificate to keychain
security import $DEVELOPER_ID_APPLICATION_CERTIFICATE_PATH -P "$P12_PASSWORD" -A -t cert -f pkcs12 -k $KEYCHAIN_PATH
security list-keychain -d user -s $KEYCHAIN_PATH
security set-key-partition-list -S apple-tool:,apple:,codesign: -s -k "$KEYCHAIN_PASSWORD" $KEYCHAIN_PATH
#2 Setup Java
- name: Set Up Java
uses: actions/setup-java@v3.12.0
@@ -32,16 +61,33 @@ jobs:
- name: Install Dependencies
run: flutter pub get
#8 Build app ( macos Build )
- name: Build App
run: flutter build macos --release
- name: Code Signing
run: /usr/bin/codesign --deep --force -s "$DEVELOPER_ID_APPLICATION_SIGNING_IDENTITY" --options runtime SwiftControl.app -v
working-directory: build/macos/Build/Products/Release
env:
DEVELOPER_ID_APPLICATION_SIGNING_IDENTITY: ${{ secrets.DEVELOPER_ID_APPLICATION_SIGNING_IDENTITY }}
- name: Decode Keystore
run: |
echo "${{ secrets.KEYSTORE_BASE64 }}" | base64 --decode > android/android.keystore;
echo "${{ secrets.KEYSTORE_PROPERTIES }}" > android/keystore.properties;
#6 Building APK
- name: Build APK
run: flutter build apk --release
#8 Build app ( macos Build )
- name: Build IPA
run: flutter build macos --release
- name: Build Web
run: flutter build web --release
run: flutter build web --release --base-href "/swiftcontrol/"
- name: Handle archives
run: |
cp build/app/outputs/flutter-apk/app-release.apk build/app/outputs/flutter-apk/SwiftControl.android.apk
cd build/macos/Build/Products/Release/
zip -r SwiftControl.macos.zip SwiftControl.app/
#9 Upload Artifacts
- name: Upload Artifacts
@@ -49,8 +95,8 @@ jobs:
with:
name: Releases
path: |
build/app/outputs/flutter-apk/app-release.apk
build/macos/Build/Products/Release/SwiftControl.app
build/app/outputs/flutter-apk/SwiftControl.android.apk
build/macos/Build/Products/Release/SwiftControl.macos.zip
#10 Extract Version
- name: Extract version from pubspec.yaml
@@ -81,7 +127,7 @@ jobs:
- name: Create Release
uses: ncipollo/release-action@v1
with:
artifacts: "build/app/outputs/flutter-apk/app-release.apk,build/macos/Build/Products/Release/SwiftControl.app"
artifacts: "build/app/outputs/flutter-apk/SwiftControl.android.apk,build/macos/Build/Products/Release/SwiftControl.macos.zip"
tag: v${{ env.VERSION }}
token: ${{ secrets.TOKEN }}
@@ -93,3 +139,66 @@ jobs:
- name: Web Deploy
uses: actions/deploy-pages@v4
windows:
needs: build
name: Build & Release on Windows
runs-on: windows-latest
steps:
#1 Checkout Repository
- name: Checkout Repository
uses: actions/checkout@v3
#2 Setup Java
- name: Set Up Java
uses: actions/setup-java@v3.12.0
with:
distribution: 'oracle'
java-version: '17'
#3 Setup Flutter
- name: Set Up Flutter
uses: subosito/flutter-action@v2
with:
channel: 'stable'
#4 Install Dependencies
- name: Install Dependencies
run: flutter pub get
- name: Build App
run: flutter build windows
- name: Zip directory (Windows)
shell: pwsh
run: |
Compress-Archive -Path "build/windows/x64/runner/Release/*" -DestinationPath "build/windows/x64/runner/Release/SwiftControl.windows.zip"
#9 Upload Artifacts
- name: Upload Artifacts
uses: actions/upload-artifact@v4
with:
overwrite: true
name: Releases
path: |
build/windows/x64/runner/Release/SwiftControl.windows.zip
#10 Extract Version
- name: Extract version from pubspec.yaml (Windows)
shell: pwsh
run: |
$version = Select-String '^version: ' pubspec.yaml | ForEach-Object {
($_ -split ' ')[1].Trim()
}
echo "VERSION=$version" >> $env:GITHUB_ENV
# add artifact to release
- name: Create Release
uses: ncipollo/release-action@v1
with:
allowUpdates: true
artifacts: "build/windows/x64/runner/Release/SwiftControl.windows.zip"
tag: v${{ env.VERSION }}
token: ${{ secrets.TOKEN }}

2
.gitignore vendored
View File

@@ -12,6 +12,8 @@
.swiftpm/
migrate_working_dir/
android/keystore.properties
# IntelliJ related
*.iml
*.ipr

49
CHANGELOG.md Normal file
View File

@@ -0,0 +1,49 @@
### 1.1.9 (2025-04-03)
- Add more troubleshooting during connection
### 1.1.8 (2025-04-02)
- Android: make sure the touch reassignment page is fullscreen
### 1.1.7 (2025-04-01)
- Zwift Ride: fix connection issues by connecting only to the left controller
- Windows: connect sequentially to fix (finally?) fix connection issues
- Windows: change the way keyboard is simulated, should fix glitches
### 1.1.6 (2025-03-31)
- Zwift Ride: add buttonPowerDown to shift gears
- Zwift Play: Fix buttonShift assignment
- Android: fix action to go to next song
- App now checks if you run the latest available version
### 1.1.5 (2025-03-30)
- fix bluetooth connection #6, also add missing entitlement on macOS
### 1.1.3 (2025-03-30)
- Windows: fix custom keyboard profile recreation after restart, also warn when choosing MyWhoosh profile (may fix #7)
- Zwift Ride: button map adjustments to prevent double shifting
- potential fix for #6
### 1.1.1 (2025-03-30)
- potential fix for Bluetooth device detection
### 1.1.0 (2025-03-30)
- Windows & macOS: allow setting custom keymap and store the setting
- Android: allow customizing the touch area, so it can work with any device without guesswork where the buttons are (#4)
- Zwift Ride: update Zwift Ride decoding based on Feedback from @JayyajGH (#3)
### 1.0.6 (2025-03-29)
- Another potential keyboard fix for Windows
- Zwift Play: actually also use the dedicated shift buttons
### 1.0.5 (2025-03-29)
- Zwift Ride: remap the shifter buttons to the correct values
### 1.0.0+4 (2025-03-29)
- Zwift Ride: attempt to fix button parsing
- Android: fix missing permissions
- Windows: potential fix for key press issues
### 1.0.0+3 (2025-03-29)
- Windows: fix connection by using a different Bluetooth stack (issue #1)
- Android: fix non-working touch propagation (issue #2)

View File

@@ -2,32 +2,50 @@
<img src="logo.jpg" alt="SwiftControl Logo"/>
### Description
## Description
With SwiftControl you can control your favorite trainer app using your Zwift Click, Zwift Ride or Zwift Play devices. Primarily useful to perform virtual gear shifting.
### Supported Apps
https://github.com/user-attachments/assets/1f81b674-1628-4763-ad66-5f3ed7a3f159
## Downloads
Get the latest version here: https://github.com/jonasbark/swiftcontrol/releases
## Supported Apps
- MyWhoosh
- indieVelo / Training Peaks
- let me know if you know others that can benefit
- any other:
- Android: you can customize the gear shifting touch points in the app
- Desktop: you can customize the keyboard shortcuts in the app
### Supported Devices
## Supported Devices
- Zwift Click
- Zwift Ride
- Zwift Play
### Supported Platforms
## Supported Platforms
- Android
- macOS
- Windows
- Windows (make sure you have installed the "[Microsoft Visual C++ Runtime libraries](https://learn.microsoft.com/en-us/cpp/windows/latest-supported-vc-redist?view=msvc-170)")
- [Web](https://jonasbark.github.io/swiftcontrol/) (you won't be able to do much)
### How does it work?
## Troubleshooting
Your Zwift device is found but connection does not work properly? You may need to update the firmware in Zwift Companion app.
## How does it work?
The app connects to your Zwift device automatically.
- When using Android a "click" on a certain part of the screen is simulated to trigger the action.
- When using macOS or Windows a keyboard click is used to trigger the action. Typically + and - keys are used to shift gears, while MyWhoosh uses K and I keys.
### TODO
- test Zwift Ride
## Donate
Please consider donating to support the development of this app.
[![Donate](https://img.shields.io/badge/Donate-PayPal-green.svg)](https://paypal.me/boni)
## TODO
- implement more actions for Play + Ride
- shorebird?

View File

@@ -45,6 +45,19 @@ class FlutterError (
val details: Any? = null
) : Throwable()
enum class MediaAction(val raw: Int) {
PLAY_PAUSE(0),
NEXT(1),
VOLUME_UP(2),
VOLUME_DOWN(3);
companion object {
fun ofRaw(raw: Int): MediaAction? {
return values().firstOrNull { it.raw == raw }
}
}
}
/** Generated class from Pigeon that represents data sent in messages. */
data class WindowEvent (
val packageName: String,
@@ -85,6 +98,11 @@ private open class AccessibilityApiPigeonCodec : StandardMessageCodec() {
override fun readValueOfType(type: Byte, buffer: ByteBuffer): Any? {
return when (type) {
129.toByte() -> {
return (readValue(buffer) as Long?)?.let {
MediaAction.ofRaw(it.toInt())
}
}
130.toByte() -> {
return (readValue(buffer) as? List<Any?>)?.let {
WindowEvent.fromList(it)
}
@@ -94,8 +112,12 @@ private open class AccessibilityApiPigeonCodec : StandardMessageCodec() {
}
override fun writeValue(stream: ByteArrayOutputStream, value: Any?) {
when (value) {
is WindowEvent -> {
is MediaAction -> {
stream.write(129)
writeValue(stream, value.raw)
}
is WindowEvent -> {
stream.write(130)
writeValue(stream, value.toList())
}
else -> super.writeValue(stream, value)
@@ -110,6 +132,7 @@ interface Accessibility {
fun hasPermission(): Boolean
fun openPermissions()
fun performTouch(x: Double, y: Double)
fun controlMedia(action: MediaAction)
companion object {
/** The codec used by Accessibility. */
@@ -170,6 +193,24 @@ interface Accessibility {
channel.setMessageHandler(null)
}
}
run {
val channel = BasicMessageChannel<Any?>(binaryMessenger, "dev.flutter.pigeon.accessibility.Accessibility.controlMedia$separatedMessageChannelSuffix", codec)
if (api != null) {
channel.setMessageHandler { message, reply ->
val args = message as List<Any?>
val actionArg = args[0] as MediaAction
val wrapped: List<Any?> = try {
api.controlMedia(actionArg)
listOf(null)
} catch (exception: Throwable) {
wrapError(exception)
}
reply.reply(wrapped)
}
} else {
channel.setMessageHandler(null)
}
}
}
}
}

View File

@@ -1,6 +1,7 @@
package de.jonasbark.accessibility
import Accessibility
import MediaAction
import PigeonEventSink
import StreamEventsStreamHandler
import WindowEvent
@@ -10,14 +11,11 @@ import android.os.Bundle
import android.provider.Settings
import androidx.core.content.ContextCompat.startActivity
import io.flutter.embedding.engine.plugins.FlutterPlugin
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
import io.flutter.plugin.common.MethodChannel.MethodCallHandler
import io.flutter.plugin.common.MethodChannel.Result
/** AccessibilityPlugin */
class AccessibilityPlugin: FlutterPlugin, MethodCallHandler, Accessibility {
class AccessibilityPlugin: FlutterPlugin, Accessibility {
/// The MethodChannel that will the communication between Flutter and native Android
///
/// This local reference serves to register the plugin with the Flutter Engine and unregister it
@@ -37,14 +35,6 @@ class AccessibilityPlugin: FlutterPlugin, MethodCallHandler, Accessibility {
Observable.fromService = eventHandler
}
override fun onMethodCall(call: MethodCall, result: Result) {
if (call.method == "getPlatformVersion") {
result.success("Android ${android.os.Build.VERSION.RELEASE}")
} else {
result.notImplemented()
}
}
override fun onDetachedFromEngine(binding: FlutterPlugin.FlutterPluginBinding) {
channel.setMethodCallHandler(null)
}
@@ -64,6 +54,22 @@ class AccessibilityPlugin: FlutterPlugin, MethodCallHandler, Accessibility {
Observable.toService?.performTouch(x = x, y = y) ?: error("Service not running")
}
override fun controlMedia(action: MediaAction) {
val audioService = context.getSystemService(Context.AUDIO_SERVICE) as android.media.AudioManager
when (action) {
MediaAction.PLAY_PAUSE -> {
audioService.dispatchMediaKeyEvent(android.view.KeyEvent(android.view.KeyEvent.ACTION_DOWN, android.view.KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE))
audioService.dispatchMediaKeyEvent(android.view.KeyEvent(android.view.KeyEvent.ACTION_UP, android.view.KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE))
}
MediaAction.NEXT -> {
audioService.dispatchMediaKeyEvent(android.view.KeyEvent(android.view.KeyEvent.ACTION_DOWN, android.view.KeyEvent.KEYCODE_MEDIA_NEXT))
audioService.dispatchMediaKeyEvent(android.view.KeyEvent(android.view.KeyEvent.ACTION_UP, android.view.KeyEvent.KEYCODE_MEDIA_NEXT))
}
MediaAction.VOLUME_DOWN -> audioService.adjustVolume(android.media.AudioManager.ADJUST_LOWER, android.media.AudioManager.FLAG_SHOW_UI)
MediaAction.VOLUME_UP -> audioService.adjustVolume(android.media.AudioManager.ADJUST_RAISE, android.media.AudioManager.FLAG_SHOW_UI)
}
}
}
class EventListener : StreamEventsStreamHandler(), Receiver {

View File

@@ -9,7 +9,6 @@ import android.os.Build
import android.util.Log
import android.view.ViewConfiguration
import android.view.accessibility.AccessibilityEvent
import android.view.accessibility.AccessibilityEvent.CONTENT_CHANGE_TYPE_PANE_DISAPPEARED
import android.view.accessibility.AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED
@@ -26,11 +25,13 @@ class AccessibilityService : AccessibilityService(), Listener {
Observable.toService = null
}
private val ignorePackages = listOf("com.android.systemui", "com.android.launcher", "com.android.settings")
override fun onAccessibilityEvent(event: AccessibilityEvent) {
if (event.packageName == null || rootInActiveWindow == null) {
return
}
if (event.contentChangeTypes == CONTENT_CHANGE_TYPE_PANE_DISAPPEARED) {
if (event.eventType != TYPE_WINDOW_STATE_CHANGED || event.packageName in ignorePackages) {
// we're not interested
return
}

View File

@@ -7,8 +7,12 @@ abstract class Accessibility {
void openPermissions();
void performTouch(double x, double y);
void controlMedia(MediaAction action);
}
enum MediaAction { playPause, next, volumeUp, volumeDown }
class WindowEvent {
final String packageName;
final int windowHeight;

View File

@@ -15,6 +15,13 @@ PlatformException _createConnectionError(String channelName) {
);
}
enum MediaAction {
playPause,
next,
volumeUp,
volumeDown,
}
class WindowEvent {
WindowEvent({
required this.packageName,
@@ -77,8 +84,11 @@ class _PigeonCodec extends StandardMessageCodec {
if (value is int) {
buffer.putUint8(4);
buffer.putInt64(value);
} else if (value is WindowEvent) {
} else if (value is MediaAction) {
buffer.putUint8(129);
writeValue(buffer, value.index);
} else if (value is WindowEvent) {
buffer.putUint8(130);
writeValue(buffer, value.encode());
} else {
super.writeValue(buffer, value);
@@ -89,6 +99,9 @@ class _PigeonCodec extends StandardMessageCodec {
Object? readValueOfType(int type, ReadBuffer buffer) {
switch (type) {
case 129:
final int? value = readValue(buffer) as int?;
return value == null ? null : MediaAction.values[value];
case 130:
return WindowEvent.decode(readValue(buffer)!);
default:
return super.readValueOfType(type, buffer);
@@ -184,6 +197,29 @@ class Accessibility {
return;
}
}
Future<void> controlMedia(MediaAction action) async {
final String pigeonVar_channelName = 'dev.flutter.pigeon.accessibility.Accessibility.controlMedia$pigeonVar_messageChannelSuffix';
final BasicMessageChannel<Object?> pigeonVar_channel = BasicMessageChannel<Object?>(
pigeonVar_channelName,
pigeonChannelCodec,
binaryMessenger: pigeonVar_binaryMessenger,
);
final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(<Object?>[action]);
final List<Object?>? pigeonVar_replyList =
await pigeonVar_sendFuture as List<Object?>?;
if (pigeonVar_replyList == null) {
throw _createConnectionError(pigeonVar_channelName);
} else if (pigeonVar_replyList.length > 1) {
throw PlatformException(
code: pigeonVar_replyList[0]! as String,
message: pigeonVar_replyList[1] as String?,
details: pigeonVar_replyList[2],
);
} else {
return;
}
}
}
Stream<WindowEvent> streamEvents( {String instanceName = ''}) {

View File

@@ -1,3 +1,6 @@
import java.io.FileInputStream
import java.util.*
plugins {
id("com.android.application")
id("kotlin-android")
@@ -5,6 +8,11 @@ plugins {
id("dev.flutter.flutter-gradle-plugin")
}
val keystorePropertiesFile = rootProject.file("keystore.properties")
val keystoreProperties = Properties()
keystoreProperties.load(FileInputStream(keystorePropertiesFile))
android {
namespace = "de.jonasbark.swift_play"
compileSdk = flutter.compileSdkVersion
@@ -33,11 +41,18 @@ android {
versionName = flutter.versionName
}
signingConfigs {
create("config") {
keyAlias = keystoreProperties["keyAlias"] as String
keyPassword = keystoreProperties["keyPassword"] as String
storeFile = file("../${keystoreProperties["storeFile"] as String}")
storePassword = keystoreProperties["storePassword"] as String
}
}
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")
signingConfig = signingConfigs.getByName("config")
}
}
}

View File

@@ -19,6 +19,9 @@
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" android:maxSdkVersion="28" />
<uses-permission android:name="android.permission.POST_NOTIFICATIONS"/>
<!-- to check if you have the latest version -->
<uses-permission android:name="android.permission.INTERNET" />
<application
android:label="SwiftControl"
android:name="${applicationName}"

View File

@@ -1,29 +0,0 @@
---
name: Bug Report
about: Create a report to help us improve
title: "fix: "
labels: bug
---
**Description**
A clear and concise description of what the bug is.
**Steps To Reproduce**
1. Go to '...'
2. Click on '....'
3. Scroll down to '....'
4. See error
**Expected Behavior**
A clear and concise description of what you expected to happen.
**Screenshots**
If applicable, add screenshots to help explain your problem.
**Additional Context**
Add any other context about the problem here.

View File

@@ -1,14 +0,0 @@
---
name: Build System
about: Changes that affect the build system or external dependencies
title: "build: "
labels: build
---
**Description**
Describe what changes need to be done to the build system and why.
**Requirements**
- [ ] The build system is passing

View File

@@ -1,14 +0,0 @@
---
name: Chore
about: Other changes that don't modify src or test files
title: "chore: "
labels: chore
---
**Description**
Clearly describe what change is needed and why. If this changes code then please use another issue type.
**Requirements**
- [ ] No functional changes to the code

View File

@@ -1,14 +0,0 @@
---
name: Continuous Integration
about: Changes to the CI configuration files and scripts
title: "ci: "
labels: ci
---
**Description**
Describe what changes need to be done to the ci/cd system and why.
**Requirements**
- [ ] The ci system is passing

View File

@@ -1 +0,0 @@
blank_issues_enabled: false

View File

@@ -1,14 +0,0 @@
---
name: Documentation
about: Improve the documentation so all collaborators have a common understanding
title: "docs: "
labels: documentation
---
**Description**
Clearly describe what documentation you are looking to add or improve.
**Requirements**
- [ ] Requirements go here

View File

@@ -1,18 +0,0 @@
---
name: Feature Request
about: A new feature to be added to the project
title: "feat: "
labels: feature
---
**Description**
Clearly describe what you are looking to add. The more context the better.
**Requirements**
- [ ] Checklist of requirements to be fulfilled
**Additional Context**
Add any other context or screenshots about the feature request go here.

View File

@@ -1,14 +0,0 @@
---
name: Performance Update
about: A code change that improves performance
title: "perf: "
labels: performance
---
**Description**
Clearly describe what code needs to be changed and what the performance impact is going to be. Bonus point's if you can tie this directly to user experience.
**Requirements**
- [ ] There is no drop in test coverage.

View File

@@ -1,14 +0,0 @@
---
name: Refactor
about: A code change that neither fixes a bug nor adds a feature
title: "refactor: "
labels: refactor
---
**Description**
Clearly describe what needs to be refactored and why. Please provide links to related issues (bugs or upcoming features) in order to help prioritize.
**Requirements**
- [ ] There is no drop in test coverage.

View File

@@ -1,16 +0,0 @@
---
name: Revert Commit
about: Reverts a previous commit
title: "revert: "
labels: revert
---
**Description**
Provide a link to a PR/Commit that you are looking to revert and why.
**Requirements**
- [ ] Change has been reverted
- [ ] No change in test coverage has happened
- [ ] A new ticket is created for any follow on work that needs to happen

View File

@@ -1,14 +0,0 @@
---
name: Style Changes
about: Changes that do not affect the meaning of the code (white space, formatting, missing semi-colons, etc)
title: "style: "
labels: style
---
**Description**
Clearly describe what you are looking to change and why.
**Requirements**
- [ ] There is no drop in test coverage.

View File

@@ -1,14 +0,0 @@
---
name: Test
about: Adding missing tests or correcting existing tests
title: "test: "
labels: test
---
**Description**
List out the tests that need to be added or changed. Please also include any information as to why this was not covered in the past.
**Requirements**
- [ ] There is no drop in test coverage.

View File

@@ -1,27 +0,0 @@
<!--
Thanks for contributing!
Provide a description of your changes below and a general summary in the title
Please look at the following checklist to ensure that your PR can be accepted quickly:
-->
## Status
**READY/IN DEVELOPMENT/HOLD**
## Description
<!--- Describe your changes in detail -->
## Type of Change
<!--- Put an `x` in all the boxes that apply: -->
- [ ] ✨ New feature (non-breaking change which adds functionality)
- [ ] 🛠️ Bug fix (non-breaking change which fixes an issue)
- [ ] ❌ Breaking change (fix or feature that would cause existing functionality to change)
- [ ] 🧹 Code refactor
- [ ] ✅ Build configuration change
- [ ] 📝 Documentation
- [ ] 🗑️ Chore

View File

@@ -1,21 +0,0 @@
{
"version": "0.2",
"$schema": "https://raw.githubusercontent.com/streetsidesoftware/cspell/main/cspell.schema.json",
"dictionaries": ["vgv_allowed", "vgv_forbidden"],
"dictionaryDefinitions": [
{
"name": "vgv_allowed",
"path": "https://raw.githubusercontent.com/verygoodopensource/very_good_dictionaries/main/allowed.txt",
"description": "Allowed VGV Spellings"
},
{
"name": "vgv_forbidden",
"path": "https://raw.githubusercontent.com/verygoodopensource/very_good_dictionaries/main/forbidden.txt",
"description": "Forbidden VGV Spellings"
}
],
"useGitignore": true,
"words": [
"flutter_blue_plus_windows"
]
}

View File

@@ -1,11 +0,0 @@
version: 2
enable-beta-ecosystems: true
updates:
- package-ecosystem: "github-actions"
directory: "/"
schedule:
interval: "daily"
- package-ecosystem: "pub"
directory: "/"
schedule:
interval: "daily"

View File

@@ -1,12 +0,0 @@
# See https://www.dartlang.org/guides/libraries/private-files
# Files and directories created by pub
.dart_tool/
.packages
build/
pubspec.lock
/.idea/
/.flutter-plugins
/.flutter-plugins-dependencies
interanl_example

View File

@@ -1,106 +0,0 @@
## 1.26.1
* Add setOptions.
## 1.26.0
* Set `flutter_blue_plus` upperbound <1.35.0 (due to api changes)
## 1.25.0
* Ensure tracing connection when reconnection occurs after force disconnection.
## 1.24.22
* Upgrade FBP version to `>=1.32.4 <=1.40.0` #24.
## 1.24.21
* fix: startScan() doesn't return correct ScanResult #25
## 1.24.20
* Downgrade FBP version to `>=1.32.4 <=1.33.6` due to the breaking changes.
* After upgrade process, the dependencies will be returned to `>=1.34.4 <1.40.0` #24.
## 1.24.19
* Fix a bug with `onValueReceived` of emitting write packet #22.
## 1.24.18
* Add implementation of `BluetoothDeviceWindow.fromId()` #21.
## 1.24.15
* Fix a bug w.r.t. company ID in manufacturer data. (@betto-a #18)
## 1.24.14
* Implement cancelOnDisconnect (@jefflongo #16)
## 1.24.12
* Fix minor bug w.r.t. `characteristic.isNotifying`.
## 1.24.11
* Fix breaking changes of FBP w.r.t. `systemDevices(List withServices)`.
## 1.24.10
* Add support for `cancelWhenScanComplete`
## 1.24.9
* Implement scan filter (including `withServices`, `withRemoteIds`, `withNames`).
## 1.24.8
* Keep manufacturer data when scanning.
## 1.24.7
* Keep service uuids when scanning.
## 1.24.0
* Update `README.md`.
## 1.23.6
* Add unimplemented notification for `read` or `write`.
## 1.14.0
* Remove dependencies `ffi` and `win32` to avoid compile error for web
## 1.9.5
* Apply `flutter blue plus` to `1.28.13`.
## 1.9.0
* Apply a breaking changes `Guid` in `Flutter blue plus` packages.
* Use `uuid128` instead of `toString()`.
## 1.8.10
* Fix `Guid` bug related with `Flutter blue plus` packages.
## 1.8.0
* Fix bug with Guid converted from string due to starting/ending with '{ }' in `WinBLE`
## 1.7.0
* Apply `flutter blue plus 1.28.5` (there is several breaking changes.).
## 1.6.6
* Add cache for storing characteristics.
## 1.6.0
* Apply `Flutter blue plus 1.26.0`, (there is a breaking change with `connect()`).
## 1.5.7
* Remove connection by OS when performing `startScan`.
## 1.5.3
* Write logs when connection state stream is started/terminated.
## 1.5.2
* Fix a bug of features added in `1.5.1`
## 1.5.1
* Remove device from connected device list when device is disconnected.
## 1.5.0
* Split functionality of `disconnect` / `removeBond`.
## 1.4.0
* Implement `Subscribe/Unsubscribe Characteristic`.
## 1.1.0
* Implement `Read/Write Characteristic`.
## 1.0.5
* Change `rxdart` version to `0.27.7`.
## 1.0.0
* Initial release (using Github action).

View File

@@ -1,7 +0,0 @@
Copyright 2023 Himchan Park
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

View File

@@ -1,54 +0,0 @@
[![pub package](https://img.shields.io/pub/v/flutter_blue_plus_windows.svg)](https://pub.dartlang.org/packages/flutter_blue_plus_windows)
## Flutter Blue Plus Windows
This project is a wrapper library for `Flutter Blue Plus` and `Win_ble`.
It allows `Flutter_blue_plus` to operate on Windows.
With minimal effort, you can use Flutter Blue Plus on Windows.
## Usage
Only you need to do is change the import statement.
```dart
// instead of import 'package:flutter_blue_plus/flutter_blue_plus.dart';
import 'package:flutter_blue_plus_windows/flutter_blue_plus_windows.dart';
// Alternatively, you can hide FlutterBluePlus when importing the FBP statement
import 'package:flutter_blue_plus/flutter_blue_plus.dart' hide FlutterBluePlus;
import 'package:flutter_blue_plus_windows/flutter_blue_plus_windows.dart';
```
### Scan devices
```dart
final scannedDevices = <ScanResult>{};
const timeout = Duration(seconds: 3);
FlutterBluePlus.startScan(timeout: timeout);
final sub = FlutterBluePlus.scanResults.expand((e)=>e).listen(scannedDevices.add);
await Future.delayed(timeout);
sub.cancel();
scannedDevices.forEach(print);
```
### Connect a device
```dart
final scannedDevice = scannedDevices
.where((scanResult) => scanResult.device.platformName == DEVICE_NAME)
.firstOrNull;
final device = scannedDevice?.device;
device?.connect();
```
### Disconnect the device
```dart
device?.disconnect();
```
Check out the usage of Flutter Blue Plus on [Flutter Blue Plus](https://pub.dev/packages/flutter_blue_plus)

View File

@@ -1,7 +0,0 @@
library flutter_blue_plus_windows;
export 'package:flutter_blue_plus/flutter_blue_plus.dart' hide FlutterBluePlus;
export 'package:win_ble/win_ble.dart';
export 'package:win_ble/win_file.dart';
export 'src/flutter_blue_plus_windows.dart';

View File

@@ -1,19 +0,0 @@
import 'package:flutter_blue_plus/flutter_blue_plus.dart';
import 'package:win_ble/win_ble.dart';
extension BluetoothAdapterStateExtension on BleState {
BluetoothAdapterState toAdapterState() {
switch(this){
case BleState.On:
return BluetoothAdapterState.on;
case BleState.Off:
return BluetoothAdapterState.off;
case BleState.Unknown:
return BluetoothAdapterState.unknown;
case BleState.Disabled:
return BluetoothAdapterState.unavailable;
case BleState.Unsupported:
return BluetoothAdapterState.unauthorized;
}
}
}

View File

@@ -1,15 +0,0 @@
import 'package:flutter_blue_plus_platform_interface/flutter_blue_plus_platform_interface.dart';
import 'package:flutter_blue_plus_windows/flutter_blue_plus_windows.dart';
extension BluetoothCharacteristicExtension on BluetoothCharacteristic {
BmBluetoothCharacteristic toProto() {
return BmBluetoothCharacteristic(
remoteId: DeviceIdentifier(remoteId.str),
serviceUuid: serviceUuid,
characteristicUuid: characteristicUuid,
descriptors: [for (final d in descriptors) d.toProto()],
properties: properties.toProto(),
primaryServiceUuid: null, // TODO: API changes
);
}
}

View File

@@ -1,14 +0,0 @@
import 'package:flutter_blue_plus/flutter_blue_plus.dart';
import 'package:flutter_blue_plus_platform_interface/flutter_blue_plus_platform_interface.dart';
extension BluetoothDescriptorExtension on BluetoothDescriptor {
BmBluetoothDescriptor toProto() {
return BmBluetoothDescriptor(
remoteId: DeviceIdentifier(remoteId.str),
serviceUuid: serviceUuid,
characteristicUuid: characteristicUuid,
descriptorUuid: descriptorUuid,
primaryServiceUuid: null, // TODO: API changes
);
}
}

View File

@@ -1,13 +0,0 @@
import 'package:flutter_blue_plus_platform_interface/flutter_blue_plus_platform_interface.dart';
import 'package:flutter_blue_plus_windows/flutter_blue_plus_windows.dart';
extension BluetoothServiceExtension on BluetoothService {
BmBluetoothService toProto() {
return BmBluetoothService(
serviceUuid: serviceUuid,
remoteId: DeviceIdentifier(remoteId.str),
characteristics: [for (final c in characteristics) c.toProto()],
primaryServiceUuid: null, // TODO: API changes
);
}
}

View File

@@ -1,19 +0,0 @@
import 'package:flutter_blue_plus/flutter_blue_plus.dart';
import 'package:flutter_blue_plus_platform_interface/flutter_blue_plus_platform_interface.dart';
extension CharacteristicPropertiesExtension on CharacteristicProperties {
BmCharacteristicProperties toProto() {
return BmCharacteristicProperties(
broadcast: broadcast,
read: read,
writeWithoutResponse: writeWithoutResponse,
write: write,
notify: notify,
indicate: indicate,
authenticatedSignedWrites: authenticatedSignedWrites,
extendedProperties: extendedProperties,
notifyEncryptionRequired: notifyEncryptionRequired,
indicateEncryptionRequired: indicateEncryptionRequired,
);
}
}

View File

@@ -1,5 +0,0 @@
export 'bluetooth_adapter_state_extension.dart';
export 'bluetooth_characteristic_extension.dart';
export 'bluetooth_descriptor_extension.dart';
export 'bluetooth_service_extension.dart';
export 'characteristic_properties_extension.dart';

View File

@@ -1,3 +0,0 @@
export 'extension/extension.dart';
export 'windows/windows.dart';
export 'wrapper/wrapper.dart';

View File

@@ -1,160 +0,0 @@
part of 'windows.dart';
class BluetoothCharacteristicWindows extends BluetoothCharacteristic {
final DeviceIdentifier remoteId;
final Guid serviceUuid;
final Guid? secondaryServiceUuid;
final Guid characteristicUuid;
final List<BluetoothDescriptor> descriptors;
final Properties propertiesWinBle;
BluetoothCharacteristicWindows({
required this.remoteId,
required this.serviceUuid,
required this.characteristicUuid,
required this.descriptors,
required this.propertiesWinBle,
this.secondaryServiceUuid,
}) : super.fromProto(
BmBluetoothCharacteristic(
remoteId: DeviceIdentifier(remoteId.str),
serviceUuid: serviceUuid,
characteristicUuid: characteristicUuid,
descriptors: [
for (final descriptor in descriptors)
BmBluetoothDescriptor(
remoteId: DeviceIdentifier(descriptor.remoteId.str),
serviceUuid: descriptor.serviceUuid,
characteristicUuid: descriptor.characteristicUuid,
descriptorUuid: descriptor.uuid,
primaryServiceUuid: null, // TODO: API changes
),
],
properties: BmCharacteristicProperties(
broadcast: propertiesWinBle.broadcast ?? false,
read: propertiesWinBle.read ?? false,
writeWithoutResponse: propertiesWinBle.writeWithoutResponse ?? false,
write: propertiesWinBle.write ?? false,
notify: propertiesWinBle.notify ?? false,
indicate: propertiesWinBle.indicate ?? false,
authenticatedSignedWrites: propertiesWinBle.authenticatedSignedWrites ?? false,
// TODO: implementation missing
extendedProperties: false,
// TODO: implementation missing
notifyEncryptionRequired: false,
// TODO: implementation missing
indicateEncryptionRequired: false,
),
primaryServiceUuid: null, // TODO: API changes
),
);
String get _address => remoteId.str.toLowerCase();
String get _key => "$serviceUuid:$characteristicUuid";
FBP.BluetoothDevice get device =>
FlutterBluePlusWindows.connectedDevices.firstWhere((device) => device.remoteId == remoteId);
/// this variable is updated:
/// - anytime `read()` is called
/// - anytime `write()` is called
/// - anytime a notification arrives (if subscribed)
List<int> get lastValue => FlutterBluePlusWindows._lastChrs[remoteId]?[_key] ?? [];
/// this stream emits values:
/// - anytime `read()` is called
/// - anytime `write()` is called
/// - anytime a notification arrives (if subscribed)
/// - and when first listened to, it re-emits the last value for convenience
Stream<List<int>> get lastValueStream => _mergeStreams(
[
WinBle.characteristicValueStreamOf(
address: _address,
serviceId: serviceUuid.str128,
characteristicId: characteristicUuid.str128,
),
FlutterBluePlusWindows._charReadWriteStream.where((e) => e.$1 == _key).map((e) => e.$2)
],
).map((p) => <int>[...p]).newStreamWithInitialValue(lastValue).asBroadcastStream();
/// this stream emits values:
/// - anytime `read()` is called
/// - anytime a notification arrives (if subscribed)
Stream<List<int>> get onValueReceived => _mergeStreams(
[
WinBle.characteristicValueStreamOf(
address: _address,
serviceId: serviceUuid.str128,
characteristicId: characteristicUuid.str128,
),
FlutterBluePlusWindows._charReadStream.where((e) => e.$1 == _key).map((e) => e.$2)
],
).map((p) => <int>[...p]).asBroadcastStream();
// TODO: need to verify
bool get isNotifying => FlutterBluePlusWindows._isNotifying[remoteId]?[_key] ?? false;
Future<List<int>> read({int timeout = 15}) async {
final value = await WinBle.read(
address: _address,
serviceId: serviceUuid.str128,
characteristicId: characteristicUuid.str128,
);
FlutterBluePlusWindows._charReadWriteStreamController.add((_key, value));
FlutterBluePlusWindows._charReadStreamController.add((_key, value));
FlutterBluePlusWindows._lastChrs[remoteId] ??= {};
FlutterBluePlusWindows._lastChrs[remoteId]?[_key] = value;
return value;
}
Future<void> write(List<int> value,
{bool allowLongWrite = false, bool withoutResponse = false, int timeout = 15}) async {
await WinBle.write(
address: _address,
service: serviceUuid.str128,
characteristic: characteristicUuid.str128,
data: Uint8List.fromList(value),
writeWithResponse: !withoutResponse, // propertiesWinBle.writeWithoutResponse ?? false,
);
FlutterBluePlusWindows._charReadWriteStreamController.add((_key, value));
FlutterBluePlusWindows._lastChrs[remoteId] ??= {};
FlutterBluePlusWindows._lastChrs[remoteId]?[_key] = value;
}
// TODO: need to verify
Future<bool> setNotifyValue(
bool notify, {
int timeout = 15, // TODO: missing implementation
bool forceIndications = false, // TODO: missing implementation
}) async {
/// unSubscribeFromCharacteristic
try {
await WinBle.unSubscribeFromCharacteristic(
address: _address,
serviceId: serviceUuid.str128,
characteristicId: characteristicUuid.str128,
);
} catch (e) {
log('WinBle.unSubscribeFromCharacteristic was performed '
'before setNotifyValue()');
}
/// set notify
try {
if (notify) {
await WinBle.subscribeToCharacteristic(
address: _address,
serviceId: serviceUuid.str128,
characteristicId: characteristicUuid.str128,
);
}
FlutterBluePlusWindows._isNotifying[remoteId] ??= {};
FlutterBluePlusWindows._isNotifying[remoteId]?[_key] = notify;
} catch (e) {
log(e.toString());
}
return true;
}
}

View File

@@ -1,310 +0,0 @@
// Bluetooth Device Page:
// https://github.com/boskokg/flutter_blue_plus/blob/master/lib/src/bluetooth_device.dart
part of 'windows.dart';
class BluetoothDeviceWindows extends FBP.BluetoothDevice {
BluetoothDeviceWindows({required super.remoteId});
// used for 'servicesStream' public api
final _services = StreamController<List<BluetoothServiceWindows>>.broadcast();
// used for 'isDiscoveringServices' public api
final _isDiscoveringServices = _StreamController(initialValue: false);
String get _address => remoteId.str.toLowerCase();
/// Create a device from an id
/// - to connect, this device must have been discovered by your app in a previous scan
/// - iOS uses 128-bit uuids the remoteId, e.g. e006b3a7-ef7b-4980-a668-1f8005f84383
/// - Android uses 48-bit mac addresses as the remoteId, e.g. 06:E5:28:3B:FD:E0
static FBP.BluetoothDevice fromId(String remoteId) {
if (Platform.isWindows) {
return BluetoothDeviceWindows(remoteId: DeviceIdentifier(remoteId.toUpperCase()));
}
return FBP.BluetoothDevice.fromId(remoteId);
}
/// platform name
/// - this name is kept track of by the platform
/// - this name usually persist between app restarts
/// - iOS: after you connect, iOS uses the GAP name characteristic (0x2A00)
/// if it exists. Otherwise iOS use the advertised name.
/// - Android: always uses the advertised name
String get platformName => FlutterBluePlusWindows._platformNames[remoteId] ?? "";
/// Advertised Named
/// - this is the name advertised by the device during scanning
/// - it is only available after you scan with FlutterBluePlus
/// - it is cleared when the app restarts.
/// - not all devices advertise a name
String get advName => FlutterBluePlusWindows._advNames[remoteId] ?? "";
// stream return whether or not we are currently discovering services
@Deprecated("planed for removal (Jan 2024). It can be easily implemented yourself") // deprecated on Aug 2023
Stream<bool> get isDiscoveringServices => _isDiscoveringServices.stream;
/// Get services
/// - returns empty if discoverServices() has not been called
/// or if your device does not have any services (rare)
List<BluetoothServiceWindows> get servicesList => FlutterBluePlusWindows._knownServices[remoteId] ?? [];
/// Stream of bluetooth services offered by the remote device
/// - this stream is only updated when you call discoverServices()
@Deprecated("planed for removal (Jan 2024). It can be easily implemented yourself") // deprecated on Aug 2023
Stream<List<BluetoothService>> get servicesStream {
if (FlutterBluePlusWindows._knownServices[remoteId] != null) {
return _services.stream.newStreamWithInitialValue(
FlutterBluePlusWindows._knownServices[remoteId]!,
);
} else {
return _services.stream;
}
}
/// Register a subscription to be canceled when the device is disconnected.
/// This function simplifies cleanup, so you can prevent creating duplicate stream subscriptions.
/// - this is an optional convenience function
/// - prevents accidentally creating duplicate subscriptions on each reconnection.
/// - [next] if true, the the stream will be canceled only on the *next* disconnection.
/// This is useful if you setup your subscriptions before you connect.
/// - [delayed] Note: This option is only meant for `connectionState` subscriptions.
/// When `true`, we cancel after a small delay. This ensures the `connectionState`
/// listener receives the `disconnected` event.
void cancelWhenDisconnected(StreamSubscription subscription, {bool next = false, bool delayed = false}) {
if (isConnected == false && next == false) {
subscription.cancel(); // cancel immediately if already disconnected.
} else if (delayed) {
FlutterBluePlusWindows._delayedSubscriptions[remoteId] ??= [];
FlutterBluePlusWindows._delayedSubscriptions[remoteId]!.add(subscription);
} else {
FlutterBluePlusWindows._deviceSubscriptions[remoteId] ??= [];
FlutterBluePlusWindows._deviceSubscriptions[remoteId]!.add(subscription);
}
}
/// Returns true if this device is currently connected to your app
bool get isConnected {
return FlutterBluePlusWindows.connectedDevices.contains(this);
}
/// Returns true if this device is currently disconnected from your app
bool get isDisconnected => isConnected == false;
Future<void> connect({
Duration? timeout = const Duration(seconds: 35), // TODO: implementation missing
bool autoConnect = false, // TODO: implementation missing
int? mtu = 512, // TODO: implementation missing
}) async {
try {
await WinBle.connect(_address);
FlutterBluePlusWindows._deviceSet.add(this);
} catch (e) {
log(e.toString());
}
}
Future<void> disconnect({
int androidDelay = 2000, // TODO: implementation missing
int timeout = 35, // TODO: implementation missing
bool queue = true, // TODO: implementation missing
}) async {
try {
await WinBle.disconnect(_address);
} catch (e) {
log(e.toString());
} finally {
FlutterBluePlusWindows._deviceSet.remove(this);
FlutterBluePlusWindows._deviceSubscriptions[remoteId]?.forEach((s) => s.cancel());
FlutterBluePlusWindows._deviceSubscriptions.remove(remoteId);
// use delayed to update the stream before we cancel it
Future.delayed(Duration.zero).then((_) {
FlutterBluePlusWindows._delayedSubscriptions[remoteId]?.forEach((s) => s.cancel());
FlutterBluePlusWindows._delayedSubscriptions.remove(remoteId);
});
FlutterBluePlusWindows._lastChrs[remoteId]?.clear();
FlutterBluePlusWindows._isNotifying[remoteId]?.clear();
}
}
Future<List<BluetoothService>> discoverServices({
bool subscribeToServicesChanged = true, // TODO: implementation missing
int timeout = 15, // TODO: implementation missing
}) async {
List<BluetoothServiceWindows> result = List.from(FlutterBluePlusWindows._knownServices[remoteId] ?? []);
try {
_isDiscoveringServices.add(true);
final response = await WinBle.discoverServices(_address);
FlutterBluePlusWindows._characteristicCache[remoteId] ??= <String, List<BluetoothCharacteristic>>{};
for (final serviceId in response) {
final characteristic = await WinBle.discoverCharacteristics(
address: _address,
serviceId: serviceId,
);
FlutterBluePlusWindows._characteristicCache[remoteId] ??= {};
FlutterBluePlusWindows._characteristicCache[remoteId]?[serviceId] ??= [
...characteristic.map(
(e) => BluetoothCharacteristicWindows(
remoteId: remoteId,
serviceUuid: Guid(serviceId),
characteristicUuid: Guid(e.uuid),
descriptors: [],
// TODO: implementation missing
propertiesWinBle: e.properties,
),
),
];
}
result = [
...response.map(
(p) => BluetoothServiceWindows(
remoteId: remoteId,
serviceUuid: Guid(p),
// TODO: implementation missing
isPrimary: true,
// TODO: implementation missing
characteristics: FlutterBluePlusWindows._characteristicCache[remoteId]![p]!,
// TODO: implementation missing
includedServices: [],
),
)
];
FlutterBluePlusWindows._knownServices[remoteId] = result;
_services.add(result);
} finally {
_isDiscoveringServices.add(false);
}
return result;
}
DisconnectReason? get disconnectReason {
// TODO: nothing to do
return null;
}
Stream<BluetoothConnectionState> get connectionState async* {
await FlutterBluePlusWindows._initialize();
final map = FlutterBluePlusWindows._connectionStream.latestValue;
if (map[_address] != null) {
yield map[_address]!.isConnected;
}
yield* WinBle.connectionStreamOf(_address).map((e) => e.isConnected);
}
Stream<int> get mtu async* {
bool isEmitted = false;
int retryCount = 0;
while (!isEmitted) {
if (retryCount > 3) throw "Device not found!";
retryCount++;
try {
yield await WinBle.getMaxMtuSize(_address);
isEmitted = true;
} catch (e) {
await Future.delayed(const Duration(milliseconds: 500));
log(e.toString());
}
}
}
Future<int> readRssi({int timeout = 15}) async {
return FlutterBluePlusWindows._rssiMap[remoteId] ?? -100;
}
Future<int> requestMtu(
int desiredMtu, {
double predelay = 0.35,
int timeout = 15,
}) async {
// https://github.com/rohitsangwan01/win_ble/issues/8
return await WinBle.getMaxMtuSize(_address);
}
Future<void> requestConnectionPriority({
required ConnectionPriority connectionPriorityRequest,
}) async {
// TODO: nothing to do
return;
}
/// Set the preferred connection (Android Only)
/// - [txPhy] bitwise OR of all allowed phys for Tx, e.g. (Phy.le2m.mask | Phy.leCoded.mask)
/// - [txPhy] bitwise OR of all allowed phys for Rx, e.g. (Phy.le2m.mask | Phy.leCoded.mask)
/// - [option] preferred coding to use when transmitting on Phy.leCoded
/// Please note that this is just a recommendation given to the system.
Future<void> setPreferredPhy({
required int txPhy,
required int rxPhy,
required PhyCoding option,
}) async {
// TODO: implementation missing
}
Future<void> createBond({
Uint8List? pin,
int timeout = 90, // TODO: implementation missing
}) async {
try {
await WinBle.pair(_address);
} catch (e) {
log(e.toString());
}
}
Future<void> removeBond({
int timeout = 30, // TODO: implementation missing
}) async {
try {
await WinBle.unPair(_address);
} catch (e) {
log(e.toString());
}
}
Future<void> clearGattCache() async {
// TODO: implementation missing
}
@override
bool operator ==(Object other) =>
identical(this, other) ||
(other is BluetoothDeviceWindows && runtimeType == other.runtimeType && remoteId == other.remoteId);
@override
int get hashCode => remoteId.hashCode;
@override
String toString() {
return 'BluetoothDevice{'
'remoteId: $remoteId, '
'platformName: $platformName, '
'services: ${FlutterBluePlusWindows._knownServices[remoteId]}'
'}';
}
@Deprecated('Use createBond() instead')
Future<void> pair() async => await createBond();
@Deprecated('Use remoteId instead')
DeviceIdentifier get id => remoteId;
@Deprecated('Use localName instead')
String get name => localName;
@Deprecated('Use connectionState instead')
Stream<BluetoothConnectionState> get state => connectionState;
@Deprecated('Use servicesStream instead')
Stream<List<BluetoothService>> get services => servicesStream;
}

View File

@@ -1,24 +0,0 @@
part of 'windows.dart';
class BluetoothServiceWindows extends BluetoothService {
final DeviceIdentifier remoteId;
final Guid serviceUuid;
final bool isPrimary;
final List<BluetoothCharacteristic> characteristics;
final List<BluetoothService> includedServices;
BluetoothServiceWindows({
required this.remoteId,
required this.serviceUuid,
required this.isPrimary,
required this.characteristics,
required this.includedServices,
}) : super.fromProto(
BmBluetoothService(
remoteId: DeviceIdentifier(remoteId.str),
serviceUuid: serviceUuid,
characteristics: [for (final c in characteristics) c.toProto()],
primaryServiceUuid: null,
),
);
}

View File

@@ -1,353 +0,0 @@
part of 'windows.dart';
class FlutterBluePlusWindows {
static bool _initialized = false;
static BluetoothAdapterState _state = BluetoothAdapterState.unknown;
// stream used for the isScanning public api
static final _isScanning = _StreamController(initialValue: false);
// we always keep track of these device variables
static final _platformNames = <DeviceIdentifier, String>{};
static final _advNames = <DeviceIdentifier, String>{};
static final _rssiMap = <DeviceIdentifier, int?>{};
static final _knownServices = <DeviceIdentifier, List<BluetoothServiceWindows>>{};
static final Map<DeviceIdentifier, Map<String, List<int>>> _lastChrs = {};
static final Map<DeviceIdentifier, Map<String, bool>> _isNotifying = {};
static final Map<DeviceIdentifier, Map<String, List<BluetoothCharacteristic>>> _characteristicCache = {};
static final Map<DeviceIdentifier, List<StreamSubscription>> _deviceSubscriptions = {};
static final Map<DeviceIdentifier, List<StreamSubscription>> _delayedSubscriptions = {};
static final List<StreamSubscription> _scanSubscriptions = [];
// stream used for the scanResults public api
static final _scanResultsList = _StreamController(initialValue: <ScanResult>[]);
// the subscription to the scan results stream
static StreamSubscription<BleDevice?>? _scanSubscription;
// timeout for scanning that can be cancelled by stopScan
static Timer? _scanTimeout;
static List<BluetoothDeviceWindows> get _devices => [..._deviceSet];
static final _deviceSet = <BluetoothDeviceWindows>{};
static final _removedDeviceTracer = <BluetoothDeviceWindows, StreamSubscription>{};
// static final _unhandledDeviceSet = <BluetoothDeviceWindows>{};
/// Flutter blue plus windows
static final _charReadWriteStreamController = StreamController<(String, List<int>)>();
static final _charReadStreamController = StreamController<(String, List<int>)>();
static final _charReadWriteStream = _charReadWriteStreamController.stream.asBroadcastStream();
static final _charReadStream = _charReadStreamController.stream.asBroadcastStream();
/// Flutter blue plus windows
static final _connectionStream = _StreamController(initialValue: <String, bool>{});
static Future<void> _initialize() async {
if (_initialized) return;
await WinBle.initialize(
serverPath: await WinServer.path(),
enableLog: false,
);
WinBle.connectionStream.listen(
(event) {
log('$event - event');
if (event['device'] == null) return;
if (event['connected'] == null) return;
final map = _connectionStream.latestValue;
map[event['device']] = event['connected'];
log('$map - map');
_connectionStream.add(map);
if (!event['connected']) {
final removingDevices = [
..._deviceSet.where(
(device) => device._address == event['device'],
),
];
for (final device in removingDevices) {
_deviceSet.remove(device);
if (!_removedDeviceTracer.keys.contains(device)) {
_removedDeviceTracer[device] = Stream.periodic(const Duration(seconds: 10), (_) => device).listen(
(event) {
if(event.isConnected) {
_removedDeviceTracer[device]?.cancel();
_removedDeviceTracer.remove(device);
return;
}
event.connect();
},
);
}
_deviceSubscriptions[device.remoteId]?.forEach((s) => s.cancel());
_deviceSubscriptions.remove(device.remoteId);
// use delayed to update the stream before we cancel it
Future.delayed(Duration.zero).then((_) {
_delayedSubscriptions[device.remoteId]?.forEach((s) => s.cancel());
_delayedSubscriptions.remove(device.remoteId);
});
_lastChrs[device.remoteId]?.clear();
_isNotifying[device.remoteId]?.clear();
}
}
},
);
_initialized = true;
}
static Future<bool> get isSupported async {
return true;
}
static Future<String> get adapterName async {
return 'Windows';
}
static Stream<bool> get isScanning => _isScanning.stream;
static bool get isScanningNow => _isScanning.latestValue;
static Future<void> turnOn({int timeout = 10}) async {
await _initialize();
await WinBle.updateBluetoothState(true);
}
// TODO: compare with original lib
static Stream<List<ScanResult>> get scanResults => _scanResultsList.stream;
static Stream<BluetoothAdapterState> get adapterState async* {
await _initialize();
yield _state;
yield* WinBle.bleState.asBroadcastStream().map(
(s) {
_state = s.toAdapterState();
return _state;
},
);
}
/// Start a scan, and return a stream of results
/// Note: scan filters use an "or" behavior. i.e. if you set `withServices` & `withNames` we
/// return all the advertisments that match any of the specified services *or* any of the specified names.
/// - [withServices] filter by advertised services
/// - [withRemoteIds] filter for known remoteIds (iOS: 128-bit guid, android: 48-bit mac address)
/// - [withNames] filter by advertised names (exact match)
/// - [withKeywords] filter by advertised names (matches any substring)
/// - [withMsd] filter by manfacture specific data
/// - [withServiceData] filter by service data
/// - [timeout] calls stopScan after a specified duration
/// - [removeIfGone] if true, remove devices after they've stopped advertising for X duration
/// - [continuousUpdates] If `true`, we continually update 'lastSeen' & 'rssi' by processing
/// duplicate advertisements. This takes more power. You typically should not use this option.
/// - [continuousDivisor] Useful to help performance. If divisor is 3, then two-thirds of advertisements are
/// ignored, and one-third are processed. This reduces main-thread usage caused by the platform channel.
/// The scan counting is per-device so you always get the 1st advertisement from each device.
/// If divisor is 1, all advertisements are returned. This argument only matters for `continuousUpdates` mode.
/// - [oneByOne] if `true`, we will stream every advertistment one by one, possibly including duplicates.
/// If `false`, we deduplicate the advertisements, and return a list of devices.
/// - [androidLegacy] Android only. If `true`, scan on 1M phy only.
/// If `false`, scan on all supported phys. How the radio cycles through all the supported phys is purely
/// dependent on the your Bluetooth stack implementation.
/// - [androidScanMode] choose the android scan mode to use when scanning
/// - [androidUsesFineLocation] request `ACCESS_FINE_LOCATION` permission at runtime
static Future<void> startScan({
List<Guid> withServices = const [],
List<String> withRemoteIds = const [],
List<String> withNames = const [],
//TODO: implementation missing
List<String> withKeywords = const [],
//TODO: implementation missing
List<MsdFilter> withMsd = const [],
List<ServiceDataFilter> withServiceData = const [],
Duration? timeout,
Duration? removeIfGone,
bool continuousUpdates = false,
int continuousDivisor = 1,
bool oneByOne = false,
bool androidLegacy = false,
AndroidScanMode androidScanMode = AndroidScanMode.lowLatency,
bool androidUsesFineLocation = false,
}) async {
await _initialize();
// stop existing scan
if (_isScanning.latestValue == true) {
await stopScan();
}
// push to stream
_isScanning.add(true);
// Start timer *after* stream is being listened to, to make sure the
// timeout does not fire before _buffer is set
if (timeout != null) {
_scanTimeout = Timer(timeout, stopScan);
}
/// remove connection by OS.
/// The reason why we add this logic is
/// to avoid uncontrollable devices and to make consistency.
/// add WinBle scanning
WinBle.startScanning();
// check every 250ms for gone devices?
late Stream<BleDevice?> outputStream;
if (removeIfGone != null) {
outputStream = _mergeStreams([WinBle.scanStream, Stream.periodic(Duration(milliseconds: 250))]);
} else {
outputStream = WinBle.scanStream;
}
final output = <ScanResult>[];
// listen & push to `scanResults` stream
_scanSubscription = outputStream.listen(
(BleDevice? winBleDevice) {
// print(winBleDevice?.serviceUuids);
if (winBleDevice == null) {
// if null, this is just a periodic update for removing old results
output.removeWhere((elm) => DateTime.now().difference(elm.timeStamp) > removeIfGone!);
// push to stream
_scanResultsList.add(List.from(output));
} else {
final remoteId = DeviceIdentifier(winBleDevice.address.toUpperCase());
final scanResult = output.where((sr) => sr.device.remoteId == remoteId).firstOrNull;
final deviceName = winBleDevice.name.isNotEmpty ? winBleDevice.name : scanResult?.device.platformName ?? '';
final serviceUuids = winBleDevice.serviceUuids.isNotEmpty
? [...winBleDevice.serviceUuids.map((e) => Guid((e as String).replaceAll(RegExp(r'[{}]'), '')))]
: scanResult?.advertisementData.serviceUuids ?? [];
final manufacturerData = winBleDevice.manufacturerData.isNotEmpty
? {
if (winBleDevice.manufacturerData.length >= 2)
winBleDevice.manufacturerData[0] + (winBleDevice.manufacturerData[1] << 8):
winBleDevice.manufacturerData.sublist(2),
}
: scanResult?.advertisementData.manufacturerData ?? {};
final rssi = int.tryParse(winBleDevice.rssi) ?? -100;
FlutterBluePlusWindows._platformNames[remoteId] = deviceName;
FlutterBluePlusWindows._advNames[remoteId] = deviceName;
FlutterBluePlusWindows._rssiMap[remoteId] = rssi;
final device = BluetoothDeviceWindows(remoteId: remoteId);
String hex(int value) => value.toRadixString(16).padLeft(2, '0');
String hexToId(Iterable<int> values) => values.map((e) => hex(e)).join();
final sr = ScanResult(
device: device,
advertisementData: AdvertisementData(
advName: deviceName,
txPowerLevel: winBleDevice.adStructures?.where((e) => e.type == 10).singleOrNull?.data.firstOrNull,
//TODO: Should verify
connectable: !winBleDevice.advType.contains('Non'),
manufacturerData: manufacturerData,
serviceData: {
for (final advStructures in winBleDevice.adStructures ?? <AdStructure>[])
if (advStructures.type == 0x16 && advStructures.data.length >= 2)
Guid(hexToId(advStructures.data.sublist(0, 2).reversed)): advStructures.data.sublist(2),
for (final advStructures in winBleDevice.adStructures ?? <AdStructure>[])
if (advStructures.type == 0x20 && advStructures.data.length >= 4)
Guid(hexToId(advStructures.data.sublist(0, 4).reversed)): advStructures.data.sublist(4),
for (final advStructures in winBleDevice.adStructures ?? <AdStructure>[])
if (advStructures.type == 0x21 && advStructures.data.length >= 16)
Guid(hexToId(advStructures.data.sublist(0, 16).reversed)): advStructures.data.sublist(16),
},
serviceUuids: serviceUuids,
appearance: null,
),
rssi: rssi,
timeStamp: DateTime.now(),
);
// filter with services
final isFilteredWithServices =
withServices.isNotEmpty && serviceUuids.where((service) => withServices.contains(service)).isEmpty;
// filter with remote ids
final isFilteredWithRemoteIds = withRemoteIds.isNotEmpty && !withRemoteIds.contains(remoteId);
// filter with names
final isFilteredWithNames = withNames.isNotEmpty && !withNames.contains(deviceName);
if (isFilteredWithServices || isFilteredWithRemoteIds || isFilteredWithNames) {
_scanResultsList.add(List.from(output));
return;
}
// add result to output
if (oneByOne) {
output
..clear()
..add(sr);
} else {
output.addOrUpdate(sr);
}
// push to stream
_scanResultsList.add(List.from(output));
}
},
);
}
static List<FBP.BluetoothDevice> get connectedDevices {
return _devices;
}
static Future<List<BluetoothDeviceWindows>> get bondedDevices async {
return _devices;
}
/// Stops a scan for Bluetooth Low Energy devices
static Future<void> stopScan() async {
await _initialize();
WinBle.stopScanning();
_scanSubscription?.cancel();
_scanTimeout?.cancel();
_isScanning.add(false);
for (var subscription in _scanSubscriptions) {
subscription.cancel();
}
_scanResultsList.latestValue = [];
}
/// Register a subscription to be canceled when scanning is complete.
/// This function simplifies cleanup, so you can prevent creating duplicate stream subscriptions.
/// - this is an optional convenience function
/// - prevents accidentally creating duplicate subscriptions before each scan
static void cancelWhenScanComplete(StreamSubscription subscription) {
_scanSubscriptions.add(subscription);
}
/// Sets the internal FlutterBlue log level
static Future<void> setLogLevel(LogLevel level, {color = true}) async {
// Nothing to implement
return;
}
static Future<void> turnOff({int timeout = 10}) async {
await _initialize();
await WinBle.updateBluetoothState(false);
}
// TODO: need to test
static Future<bool> get isOn async {
await _initialize();
return await WinBle.bleState.asBroadcastStream().first == BleState.On;
}
}

View File

@@ -1,433 +0,0 @@
part of 'windows.dart';
String _hexEncode(List<int> numbers) {
return numbers
.map((n) => (n & 0xFF).toRadixString(16).padLeft(2, '0'))
.join();
}
List<int> _hexDecode(String hex) {
List<int> numbers = [];
for (int i = 0; i < hex.length; i += 2) {
String hexPart = hex.substring(i, i + 2);
int num = int.parse(hexPart, radix: 16);
numbers.add(num);
}
return numbers;
}
int _compareAsciiLowerCase(String a, String b) {
const int upperCaseA = 0x41;
const int upperCaseZ = 0x5a;
const int asciiCaseBit = 0x20;
var defaultResult = 0;
for (var i = 0; i < a.length; i++) {
if (i >= b.length) return 1;
var aChar = a.codeUnitAt(i);
var bChar = b.codeUnitAt(i);
if (aChar == bChar) continue;
var aLowerCase = aChar;
var bLowerCase = bChar;
// Upper case if ASCII letters.
if (upperCaseA <= bChar && bChar <= upperCaseZ) {
bLowerCase += asciiCaseBit;
}
if (upperCaseA <= aChar && aChar <= upperCaseZ) {
aLowerCase += asciiCaseBit;
}
if (aLowerCase != bLowerCase) return (aLowerCase - bLowerCase).sign;
if (defaultResult == 0) defaultResult = aChar - bChar;
}
if (b.length > a.length) return -1;
return defaultResult.sign;
}
// This is a reimplementation of BehaviorSubject from RxDart library.
// It is essentially a stream but:
// 1. we cache the latestValue of the stream
// 2. the "latestValue" is re-emitted whenever the stream is listened to
class _StreamController<T> {
T latestValue;
final StreamController<T> _controller = StreamController<T>.broadcast();
_StreamController({required T initialValue})
: this.latestValue = initialValue;
Stream<T> get stream => _controller.stream;
T get value => latestValue;
void add(T newValue) {
latestValue = newValue;
_controller.add(newValue);
}
void listen(Function(T) onData,
{Function? onError, void Function()? onDone, bool? cancelOnError}) {
onData(latestValue);
_controller.stream.listen(onData,
onError: onError, onDone: onDone, cancelOnError: cancelOnError);
}
Future<void> close() {
return _controller.close();
}
}
// imediately starts listening to a broadcast stream and
// buffering it in a new single-subscription stream
class _BufferStream<T> {
final Stream<T> _inputStream;
late final StreamSubscription? _subscription;
late final StreamController<T> _controller;
late bool hasReceivedValue = false;
_BufferStream.listen(this._inputStream) {
_controller = StreamController<T>(
onCancel: () {
_subscription?.cancel();
},
onPause: () {
_subscription?.pause();
},
onResume: () {
_subscription?.resume();
},
onListen: () {}, // inputStream is already listened to
);
// immediately start listening to the inputStream
_subscription = _inputStream.listen(
(data) {
hasReceivedValue = true;
_controller.add(data);
},
onError: (e) {
_controller.addError(e);
},
onDone: () {
_controller.close();
},
cancelOnError: false,
);
}
void close() {
_subscription?.cancel();
_controller.close();
}
Stream<T> get stream async* {
yield* _controller.stream;
}
}
// helper for 'doOnDone' method for streams.
class _OnDoneTransformer<T> extends StreamTransformerBase<T, T> {
final Function onDone;
_OnDoneTransformer({required this.onDone});
@override
Stream<T> bind(Stream<T> stream) {
if (stream.isBroadcast) {
return _bindBroadcast(stream);
}
return _bindSingleSubscription(stream);
}
Stream<T> _bindSingleSubscription(Stream<T> stream) {
StreamController<T>? controller;
StreamSubscription<T>? subscription;
controller = StreamController<T>(
onListen: () {
subscription = stream.listen(
controller?.add,
onError: controller?.addError,
onDone: () {
onDone();
controller?.close();
},
);
},
onPause: ([Future<dynamic>? resumeSignal]) {
subscription?.pause(resumeSignal);
},
onResume: () {
subscription?.resume();
},
onCancel: () {
return subscription?.cancel();
},
sync: true,
);
return controller.stream;
}
Stream<T> _bindBroadcast(Stream<T> stream) {
StreamController<T>? controller;
StreamSubscription<T>? subscription;
controller = StreamController<T>.broadcast(
onListen: () {
subscription = stream
.listen(controller?.add, onError: controller?.addError, onDone: () {
onDone();
controller?.close();
});
},
onCancel: () {
subscription?.cancel();
},
sync: true,
);
return controller.stream;
}
}
// helper for 'doOnCancel' method for streams.
class _OnCancelTransformer<T> extends StreamTransformerBase<T, T> {
final Function onCancel;
_OnCancelTransformer({required this.onCancel});
@override
Stream<T> bind(Stream<T> stream) {
if (stream.isBroadcast) {
return _bindBroadcast(stream);
}
return _bindSingleSubscription(stream);
}
Stream<T> _bindSingleSubscription(Stream<T> stream) {
StreamController<T>? controller;
StreamSubscription<T>? subscription;
controller = StreamController<T>(
onListen: () {
subscription = stream.listen(
controller?.add,
onError: (Object error) {
controller?.addError(error);
controller?.close();
},
onDone: controller?.close,
);
},
onPause: ([Future<dynamic>? resumeSignal]) {
subscription?.pause(resumeSignal);
},
onResume: () {
subscription?.resume();
},
onCancel: () {
onCancel();
return subscription?.cancel();
},
sync: true,
);
return controller.stream;
}
Stream<T> _bindBroadcast(Stream<T> stream) {
StreamController<T>? controller;
StreamSubscription<T>? subscription;
controller = StreamController<T>.broadcast(
onListen: () {
subscription = stream.listen(
controller?.add,
onError: (Object error) {
controller?.addError(error);
controller?.close();
},
onDone: controller?.close,
);
},
onCancel: () {
onCancel();
subscription?.cancel();
},
sync: true,
);
return controller.stream;
}
}
// Helper for 'newStreamWithInitialValue' method for streams.
class _NewStreamWithInitialValueTransformer<T>
extends StreamTransformerBase<T, T> {
final T initialValue;
_NewStreamWithInitialValueTransformer(this.initialValue);
@override
Stream<T> bind(Stream<T> stream) {
return _bindSingleSubscription(stream);
}
Stream<T> _bindSingleSubscription(Stream<T> stream) {
StreamController<T>? controller;
StreamSubscription<T>? subscription;
controller = StreamController<T>(
onListen: () {
// Emit the initial value
controller?.add(initialValue);
subscription = stream.listen(
controller?.add,
onError: (Object error) {
controller?.addError(error);
controller?.close();
},
onDone: controller?.close,
);
},
onPause: ([Future<dynamic>? resumeSignal]) {
subscription?.pause(resumeSignal);
},
onResume: () {
subscription?.resume();
},
onCancel: () {
return subscription?.cancel();
},
sync: true,
);
return controller.stream;
}
}
extension _StreamDoOnDone<T> on Stream<T> {
// ignore: unused_element
Stream<T> doOnDone(void Function() onDone) {
return transform(_OnDoneTransformer(onDone: onDone));
}
}
extension _StreamDoOnCancel<T> on Stream<T> {
// ignore: unused_element
Stream<T> doOnCancel(void Function() onCancel) {
return transform(_OnCancelTransformer(onCancel: onCancel));
}
}
extension _StreamNewStreamWithInitialValue<T> on Stream<T> {
Stream<T> newStreamWithInitialValue(T initialValue) {
return transform(_NewStreamWithInitialValueTransformer(initialValue));
}
}
// ignore: unused_element
Stream<T> _mergeStreams<T>(List<Stream<T>> streams) {
StreamController<T> controller = StreamController<T>();
List<StreamSubscription<T>> subscriptions = [];
void handleData(T data) {
if (!controller.isClosed) {
controller.add(data);
}
}
void handleError(Object error, StackTrace stackTrace) {
if (!controller.isClosed) {
controller.addError(error, stackTrace);
}
}
void handleDone() {
if (subscriptions.every((s) => s.isPaused)) {
controller.close();
}
}
void subscribeToStream(Stream<T> stream) {
final s =
stream.listen(handleData, onError: handleError, onDone: handleDone);
subscriptions.add(s);
}
streams.forEach(subscribeToStream);
controller.onCancel = () async {
await Future.wait(subscriptions.map((s) => s.cancel()));
};
return controller.stream;
}
// dart is single threaded, but still has task switching.
// this mutex lets a single task through at a time.
class _Mutex {
final StreamController _controller = StreamController.broadcast();
int current = 0;
int issued = 0;
Future<void> take() async {
int mine = issued;
issued++;
// tasks are executed in the same order they call take()
while (mine != current) {
await _controller.stream.first; // wait
}
}
void give() {
current++;
_controller.add(null); // release waiting tasks
}
}
// Create mutexes in a parrallel-safe way,
class _MutexFactory {
static final _Mutex _global = _Mutex();
static final Map<String, _Mutex> _all = {};
static Future<_Mutex> getMutexForKey(String key) async {
_Mutex? value;
await _global.take();
{
_all[key] ??= _Mutex();
value = _all[key];
}
_global.give();
return value!;
}
}
String _black(String s) {
// Use ANSI escape codes
return '\x1B[1;30m$s\x1B[0m';
}
// ignore: unused_element
String _green(String s) {
// Use ANSI escape codes
return '\x1B[1;32m$s\x1B[0m';
}
String _magenta(String s) {
// Use ANSI escape codes
return '\x1B[1;35m$s\x1B[0m';
}
String _brown(String s) {
// Use ANSI escape codes
return '\x1B[1;33m$s\x1B[0m';
}
extension Boolean2ConnectionState on bool {
BluetoothConnectionState get isConnected {
if (this) return BluetoothConnectionState.connected;
return BluetoothConnectionState.disconnected;
}
}

View File

@@ -1,14 +0,0 @@
import 'dart:async';
import 'dart:developer';
import 'dart:io';
import 'dart:typed_data';
import 'package:flutter_blue_plus/flutter_blue_plus.dart' as FBP;
import 'package:flutter_blue_plus_platform_interface/flutter_blue_plus_platform_interface.dart';
import 'package:flutter_blue_plus_windows/flutter_blue_plus_windows.dart';
part 'bluetooth_characteristic_windows.dart';
part 'bluetooth_device_windows.dart';
part 'bluetooth_service_windows.dart';
part 'flutter_blue_plus_windows.dart';
part 'util.dart';

View File

@@ -1,141 +0,0 @@
import 'dart:async';
import 'dart:io';
import 'package:flutter/foundation.dart';
import 'package:flutter_blue_plus/flutter_blue_plus.dart' as FBP;
import 'package:flutter_blue_plus_windows/flutter_blue_plus_windows.dart';
class FlutterBluePlus {
static Future<void> startScan({
List<Guid> withServices = const [],
List<String> withRemoteIds = const [],
List<String> withNames = const [],
List<String> withKeywords = const [],
List<MsdFilter> withMsd = const [],
List<ServiceDataFilter> withServiceData = const [],
Duration? timeout,
Duration? removeIfGone,
bool continuousUpdates = false,
int continuousDivisor = 1,
bool oneByOne = false,
bool androidLegacy = false,
AndroidScanMode androidScanMode = AndroidScanMode.lowLatency,
bool androidUsesFineLocation = false,
List<Guid> webOptionalServices = const [],
}) async {
if (!kIsWeb && Platform.isWindows) {
return await FlutterBluePlusWindows.startScan(
withServices: withServices,
withRemoteIds: withRemoteIds,
withNames: withNames,
withKeywords: withKeywords,
withMsd: withMsd,
withServiceData: withServiceData,
timeout: timeout,
removeIfGone: removeIfGone,
continuousUpdates: continuousUpdates,
continuousDivisor: continuousDivisor,
oneByOne: oneByOne,
androidLegacy: androidLegacy,
androidScanMode: androidScanMode,
androidUsesFineLocation: androidUsesFineLocation,
);
}
return await FBP.FlutterBluePlus.startScan(
withServices: withServices,
withRemoteIds: withRemoteIds,
withNames: withNames,
withKeywords: withKeywords,
withMsd: withMsd,
withServiceData: withServiceData,
timeout: timeout,
removeIfGone: removeIfGone,
continuousUpdates: continuousUpdates,
continuousDivisor: continuousDivisor,
oneByOne: oneByOne,
androidLegacy: androidLegacy,
androidScanMode: androidScanMode,
androidUsesFineLocation: androidUsesFineLocation,
webOptionalServices: webOptionalServices,
);
}
static Stream<BluetoothAdapterState> get adapterState {
if (!kIsWeb && Platform.isWindows) return FlutterBluePlusWindows.adapterState;
return FBP.FlutterBluePlus.adapterState;
}
static Stream<List<ScanResult>> get scanResults {
if (!kIsWeb && Platform.isWindows) return FlutterBluePlusWindows.scanResults;
return FBP.FlutterBluePlus.scanResults;
}
static bool get isScanningNow {
if (!kIsWeb && Platform.isWindows) return FlutterBluePlusWindows.isScanningNow;
return FBP.FlutterBluePlus.isScanningNow;
}
static Stream<bool> get isScanning {
if (!kIsWeb && Platform.isWindows) return FlutterBluePlusWindows.isScanning;
return FBP.FlutterBluePlus.isScanning;
}
static Future<void> stopScan() async {
if (!kIsWeb && Platform.isWindows) return await FlutterBluePlusWindows.stopScan();
return await FBP.FlutterBluePlus.stopScan();
}
static Future<void> setLogLevel(LogLevel level, {color = true}) async {
if (!kIsWeb && Platform.isWindows) return FlutterBluePlusWindows.setLogLevel(level, color: color);
return FBP.FlutterBluePlus.setLogLevel(level, color: color);
}
/// TODO: need to verify
static LogLevel get logLevel => FBP.FlutterBluePlus.logLevel;
static Future<void> setOptions({bool restoreState = false, bool showPowerAlert = true}) async {
if (!kIsWeb && Platform.isWindows) return;
FBP.FlutterBluePlus.setOptions(restoreState: restoreState, showPowerAlert: showPowerAlert);
}
static Future<bool> get isSupported async {
if (!kIsWeb && Platform.isWindows) return await FlutterBluePlusWindows.isSupported;
return await FBP.FlutterBluePlus.isSupported;
}
static Future<String> get adapterName async {
if (!kIsWeb && Platform.isWindows) return await FlutterBluePlusWindows.adapterName;
return await FBP.FlutterBluePlus.adapterName;
}
static Future<void> turnOn({int timeout = 60}) async {
if (!kIsWeb && Platform.isWindows) return await FlutterBluePlusWindows.turnOn(timeout: timeout);
return await FBP.FlutterBluePlus.turnOn(timeout: timeout);
}
static List<FBP.BluetoothDevice> get connectedDevices {
if (!kIsWeb && Platform.isWindows) return FlutterBluePlusWindows.connectedDevices;
return FBP.FlutterBluePlus.connectedDevices;
}
static Future<List<FBP.BluetoothDevice>> systemDevices(List<Guid> withServices) async {
//TODO: connected devices => system devices
if (!kIsWeb && Platform.isWindows) return FlutterBluePlusWindows.connectedDevices;
return await FBP.FlutterBluePlus.systemDevices(withServices);
}
static Future<PhySupport> getPhySupport() {
return FBP.FlutterBluePlus.getPhySupport();
}
static Future<List<FBP.BluetoothDevice>> get bondedDevices async {
if (!kIsWeb && Platform.isWindows) return FlutterBluePlusWindows.connectedDevices;
return await FBP.FlutterBluePlus.bondedDevices;
}
static void cancelWhenScanComplete(StreamSubscription subscription) {
if (!kIsWeb && Platform.isWindows) return FlutterBluePlusWindows.cancelWhenScanComplete(subscription);
return FBP.FlutterBluePlus.cancelWhenScanComplete(subscription);
}
}

View File

@@ -1 +0,0 @@
export 'flutter_blue_plus_wrapper.dart';

View File

@@ -1,13 +0,0 @@
name: flutter_blue_plus_windows
description: Flutter blue plus for Windows
version: 1.26.1
repository: https://github.com/chan150/flutter_blue_plus_windows
#publish_to: none
environment:
sdk: ">=3.0.0 <4.0.0"
dependencies:
flutter_blue_plus: ">=1.32.4"
win_ble: ">=1.1.1"
stream_with_value: ">=0.5.0"

View File

@@ -0,0 +1,12 @@
# Defines the Chromium style for automatic reformatting.
# http://clang.llvm.org/docs/ClangFormatStyleOptions.html
BasedOnStyle: Chromium
# This defaults to 'Auto'. Explicitly set it for a while, so that
# 'vector<vector<int> >' in existing files gets formatted to
# 'vector<vector<int>>'. ('Auto' means that clang-format will only use
# 'int>>' if the file already contains at least one such instance.)
Standard: Cpp11
SortIncludes: true
---
Language: ObjC
ColumnLimit: 100

View File

@@ -0,0 +1 @@
liberapay: lijy91

View File

@@ -0,0 +1,50 @@
name: build
on:
push:
branches: [main, dev]
pull_request:
branches: [main]
jobs:
build-macos:
runs-on: macos-latest
steps:
- uses: actions/checkout@v3
- uses: subosito/flutter-action@v2
with:
flutter-version: "3.16.8"
channel: "stable"
- uses: bluefireteam/melos-action@v2
- working-directory: ./packages/keypress_simulator/example
run: |
melos bs
flutter build macos --release
build-web:
runs-on: macos-latest
steps:
- uses: actions/checkout@v3
- uses: subosito/flutter-action@v2
with:
flutter-version: "3.16.8"
channel: "stable"
- uses: bluefireteam/melos-action@v2
- working-directory: ./packages/keypress_simulator/example
run: |
melos bs
flutter build web --release
build-windows:
runs-on: windows-latest
steps:
- uses: actions/checkout@v3
- uses: subosito/flutter-action@v2
with:
flutter-version: "3.16.8"
channel: "stable"
- uses: bluefireteam/melos-action@v2
- working-directory: ./packages/keypress_simulator/example
run: |
melos bs
flutter build windows --release

View File

@@ -0,0 +1,31 @@
name: lint
on:
push:
branches: [main, dev]
pull_request:
branches: [main]
jobs:
analyze:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: subosito/flutter-action@v2
with:
flutter-version: "3.16.8"
channel: "stable"
- uses: bluefireteam/melos-action@v2
- run: melos run analyze
format:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: subosito/flutter-action@v2
with:
flutter-version: "3.16.8"
channel: "stable"
cache: true
- uses: bluefireteam/melos-action@v2
- run: melos run format-check

View File

@@ -0,0 +1,20 @@
name: test
on:
push:
branches: [main, dev]
pull_request:
branches: [main]
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: subosito/flutter-action@v2
with:
flutter-version: "3.16.8"
channel: "stable"
cache: true
- uses: bluefireteam/melos-action@v2
- run: melos run test --no-select

6
keypress_simulator/.gitignore vendored Normal file
View File

@@ -0,0 +1,6 @@
.dart_tool/
.idea/
*.iml
pubspec_overrides.yaml
pubspec.lock

View File

@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2022-2024 LiJianying <lijy91@foxmail.com>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View File

@@ -0,0 +1,93 @@
> **🚀 快速发布您的应用**: 试试 [Fastforge](https://fastforge.dev) - 构建、打包和分发您的 Flutter 应用最简单的方式。
# keypress_simulator
[![pub version][pub-image]][pub-url] [![][discord-image]][discord-url]
[pub-image]: https://img.shields.io/pub/v/keypress_simulator.svg
[pub-url]: https://pub.dev/packages/keypress_simulator
[discord-image]: https://img.shields.io/discord/884679008049037342.svg
[discord-url]: https://discord.gg/zPa6EZ2jqb
这个插件允许 Flutter 桌面应用模拟按键操作。
---
[English](./README.md) | 简体中文
---
<!-- START doctoc generated TOC please keep comment here to allow auto update -->
<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->
- [平台支持](#%E5%B9%B3%E5%8F%B0%E6%94%AF%E6%8C%81)
- [快速开始](#%E5%BF%AB%E9%80%9F%E5%BC%80%E5%A7%8B)
- [安装](#%E5%AE%89%E8%A3%85)
- [用法](#%E7%94%A8%E6%B3%95)
- [谁在用使用它?](#%E8%B0%81%E5%9C%A8%E7%94%A8%E4%BD%BF%E7%94%A8%E5%AE%83)
- [许可证](#%E8%AE%B8%E5%8F%AF%E8%AF%81)
<!-- END doctoc generated TOC please keep comment here to allow auto update -->
## 平台支持
| Linux | macOS | Windows |
| :---: | :---: | :-----: |
| | ✔️ | ✔️ |
## 快速开始
### 安装
将此添加到你的软件包的 pubspec.yaml 文件:
```yaml
dependencies:
keypress_simulator: ^0.2.0
```
### 用法
```dart
import 'package:keypress_simulator/keypress_simulator.dart';
// 1. Simulate pressing ⌘ + C
// 1.1 Simulate key down
await keyPressSimulator.simulateKeyDown(
PhysicalKeyboardKey.keyC,
[ModifierKey.metaModifier],
);
// 1.2 Simulate key up
await keyPressSimulator.simulateKeyUp(
PhysicalKeyboardKey.keyC,
[ModifierKey.metaModifier],
);
// 2. Simulate long pressing ⌘ + space
// 2.1. Simulate key down
await keyPressSimulator.simulateKeyDown(
PhysicalKeyboardKey.space,
[ModifierKey.metaModifier],
);
await Future.delayed(const Duration(seconds: 5));
// 2.2. Simulate key up
await keyPressSimulator.simulateKeyUp(
PhysicalKeyboardKey.space,
[ModifierKey.metaModifier],
);
```
> 请看这个插件的示例应用,以了解完整的例子。
## 谁在用使用它?
- [Biyi (比译)](https://biyidev.com/) - 一个便捷的翻译和词典应用程序。
## 许可证
[MIT](./LICENSE)

View File

@@ -0,0 +1,93 @@
> **🚀 Ship Your App Faster**: Try [Fastforge](https://fastforge.dev) - The simplest way to build, package and distribute your Flutter apps.
# keypress_simulator
[![pub version][pub-image]][pub-url] [![][discord-image]][discord-url]
[pub-image]: https://img.shields.io/pub/v/keypress_simulator.svg
[pub-url]: https://pub.dev/packages/keypress_simulator
[discord-image]: https://img.shields.io/discord/884679008049037342.svg
[discord-url]: https://discord.gg/zPa6EZ2jqb
This plugin allows Flutter desktop apps to simulate key presses.
---
English | [简体中文](./README-ZH.md)
---
<!-- START doctoc generated TOC please keep comment here to allow auto update -->
<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->
- [Platform Support](#platform-support)
- [Quick Start](#quick-start)
- [Installation](#installation)
- [Usage](#usage)
- [Who's using it?](#whos-using-it)
- [License](#license)
<!-- END doctoc generated TOC please keep comment here to allow auto update -->
## Platform Support
| Linux | macOS | Windows |
| :---: | :---: | :-----: |
| | ✔️ | ✔️ |
## Quick Start
### Installation
Add this to your package's pubspec.yaml file:
```yaml
dependencies:
keypress_simulator: ^0.2.0
```
### Usage
```dart
import 'package:keypress_simulator/keypress_simulator.dart';
// 1. Simulate pressing ⌘ + C
// 1.1 Simulate key down
await keyPressSimulator.simulateKeyDown(
PhysicalKeyboardKey.keyC,
[ModifierKey.metaModifier],
);
// 1.2 Simulate key up
await keyPressSimulator.simulateKeyUp(
PhysicalKeyboardKey.keyC,
[ModifierKey.metaModifier],
);
// 2. Simulate long pressing ⌘ + space
// 2.1. Simulate key down
await keyPressSimulator.simulateKeyDown(
PhysicalKeyboardKey.space,
[ModifierKey.metaModifier],
);
await Future.delayed(const Duration(seconds: 5));
// 2.2. Simulate key up
await keyPressSimulator.simulateKeyUp(
PhysicalKeyboardKey.space,
[ModifierKey.metaModifier],
);
```
> Please see the example app of this plugin for a full example.
## Who's using it?
- [Biyi (比译)](https://biyidev.com/) - A convenient translation and dictionary app.
## License
[MIT](./LICENSE)

View File

@@ -0,0 +1,35 @@
name: keypress_simulator_workspace
repository: https://github.com/leanflutter/keypress_simulator
packages:
- examples/**
- packages/**
command:
bootstrap:
# Uses the pubspec_overrides.yaml instead of having Melos modifying the lock file.
usePubspecOverrides: true
scripts:
analyze:
exec: flutter analyze --fatal-infos
description: Run `flutter analyze` for all packages.
test:
exec: flutter test
description: Run `flutter test` for a specific package.
packageFilters:
dirExists:
- test
format:
exec: dart format . --fix
description: Run `dart format` for all packages.
format-check:
exec: dart format . --fix --set-exit-if-changed
description: Run `dart format` checks for all packages.
fix:
exec: dart fix . --apply
description: Run `dart fix` for all packages.

View File

@@ -0,0 +1,29 @@
# Miscellaneous
*.class
*.log
*.pyc
*.swp
.DS_Store
.atom/
.buildlog/
.history
.svn/
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
# Libraries should not include pubspec.lock, per https://dart.dev/guides/libraries/private-files#pubspeclock.
/pubspec.lock
**/doc/api/
.dart_tool/
build/

View File

@@ -0,0 +1,30 @@
# 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: "67457e669f79e9f8d13d7a68fe09775fefbb79f4"
channel: "stable"
project_type: plugin
# Tracks metadata for the flutter migrate command
migration:
platforms:
- platform: root
create_revision: 67457e669f79e9f8d13d7a68fe09775fefbb79f4
base_revision: 67457e669f79e9f8d13d7a68fe09775fefbb79f4
- platform: windows
create_revision: 67457e669f79e9f8d13d7a68fe09775fefbb79f4
base_revision: 67457e669f79e9f8d13d7a68fe09775fefbb79f4
# 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'

View File

@@ -0,0 +1,3 @@
## 0.2.0
* First release.

View File

@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2022-2024 LiJianying <lijy91@foxmail.com>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View File

@@ -0,0 +1,12 @@
# keypress_simulator_windows
[![pub version][pub-image]][pub-url]
[pub-image]: https://img.shields.io/pub/v/keypress_simulator_windows.svg
[pub-url]: https://pub.dev/packages/keypress_simulator_windows
The Windows implementation of [keypress_simulator](https://pub.dev/packages/keypress_simulator).
## License
[MIT](./LICENSE)

View File

@@ -0,0 +1 @@
include: package:mostly_reasonable_lints/flutter.yaml

View File

@@ -0,0 +1,25 @@
name: keypress_simulator_windows
description: Windows implementation of the keypress_simulator plugin.
version: 0.2.0
repository: https://github.com/leanflutter/keypress_simulator/tree/main/packages/keypress_simulator_windows
environment:
sdk: '>=3.0.0 <4.0.0'
flutter: '>=3.3.0'
dependencies:
flutter:
sdk: flutter
keypress_simulator_platform_interface: ^0.2.0
dev_dependencies:
flutter_test:
sdk: flutter
mostly_reasonable_lints: ^0.1.1
flutter:
plugin:
implements: keypress_simulator
platforms:
windows:
pluginClass: KeypressSimulatorWindowsPluginCApi

View File

@@ -0,0 +1,17 @@
flutter/
# Visual Studio user-specific files.
*.suo
*.user
*.userosscache
*.sln.docstates
# Visual Studio build-related files.
x64/
x86/
# Visual Studio cache files
# files ending in .cache can be ignored
*.[Cc]ache
# but keep track of directories ending in .cache
!*.[Cc]ache/

View File

@@ -0,0 +1,100 @@
# The Flutter tooling requires that developers have a version of Visual Studio
# installed that includes CMake 3.14 or later. You should not increase this
# version, as doing so will cause the plugin to fail to compile for some
# customers of the plugin.
cmake_minimum_required(VERSION 3.14)
# Project-level configuration.
set(PROJECT_NAME "keypress_simulator_windows")
project(${PROJECT_NAME} LANGUAGES CXX)
# Explicitly opt in to modern CMake behaviors to avoid warnings with recent
# versions of CMake.
cmake_policy(VERSION 3.14...3.25)
# This value is used when generating builds using this plugin, so it must
# not be changed
set(PLUGIN_NAME "keypress_simulator_windows_plugin")
# Any new source files that you add to the plugin should be added here.
list(APPEND PLUGIN_SOURCES
"keypress_simulator_windows_plugin.cpp"
"keypress_simulator_windows_plugin.h"
)
# Define the plugin library target. Its name must not be changed (see comment
# on PLUGIN_NAME above).
add_library(${PLUGIN_NAME} SHARED
"include/keypress_simulator_windows/keypress_simulator_windows_plugin_c_api.h"
"keypress_simulator_windows_plugin_c_api.cpp"
${PLUGIN_SOURCES}
)
# Apply a standard set of build settings that are configured in the
# application-level CMakeLists.txt. This can be removed for plugins that want
# full control over build settings.
apply_standard_settings(${PLUGIN_NAME})
# Symbols are hidden by default to reduce the chance of accidental conflicts
# between plugins. This should not be removed; any symbols that should be
# exported should be explicitly exported with the FLUTTER_PLUGIN_EXPORT macro.
set_target_properties(${PLUGIN_NAME} PROPERTIES
CXX_VISIBILITY_PRESET hidden)
target_compile_definitions(${PLUGIN_NAME} PRIVATE FLUTTER_PLUGIN_IMPL)
# Source include directories and library dependencies. Add any plugin-specific
# dependencies here.
target_include_directories(${PLUGIN_NAME} INTERFACE
"${CMAKE_CURRENT_SOURCE_DIR}/include")
target_link_libraries(${PLUGIN_NAME} PRIVATE flutter flutter_wrapper_plugin)
# List of absolute paths to libraries that should be bundled with the plugin.
# This list could contain prebuilt libraries, or libraries created by an
# external build triggered from this build file.
set(keypress_simulator_windows_bundled_libraries
""
PARENT_SCOPE
)
# === Tests ===
# These unit tests can be run from a terminal after building the example, or
# from Visual Studio after opening the generated solution file.
# Only enable test builds when building the example (which sets this variable)
# so that plugin clients aren't building the tests.
if (${include_${PROJECT_NAME}_tests})
set(TEST_RUNNER "${PROJECT_NAME}_test")
enable_testing()
# Add the Google Test dependency.
include(FetchContent)
FetchContent_Declare(
googletest
URL https://github.com/google/googletest/archive/release-1.11.0.zip
)
# Prevent overriding the parent project's compiler/linker settings
set(gtest_force_shared_crt ON CACHE BOOL "" FORCE)
# Disable install commands for gtest so it doesn't end up in the bundle.
set(INSTALL_GTEST OFF CACHE BOOL "Disable installation of googletest" FORCE)
FetchContent_MakeAvailable(googletest)
# The plugin's C API is not very useful for unit testing, so build the sources
# directly into the test binary rather than using the DLL.
add_executable(${TEST_RUNNER}
test/keypress_simulator_windows_plugin_test.cpp
${PLUGIN_SOURCES}
)
apply_standard_settings(${TEST_RUNNER})
target_include_directories(${TEST_RUNNER} PRIVATE "${CMAKE_CURRENT_SOURCE_DIR}")
target_link_libraries(${TEST_RUNNER} PRIVATE flutter_wrapper_plugin)
target_link_libraries(${TEST_RUNNER} PRIVATE gtest_main gmock)
# flutter_wrapper_plugin has link dependencies on the Flutter DLL.
add_custom_command(TARGET ${TEST_RUNNER} POST_BUILD
COMMAND ${CMAKE_COMMAND} -E copy_if_different
"${FLUTTER_LIBRARY}" $<TARGET_FILE_DIR:${TEST_RUNNER}>
)
# Enable automatic test discovery.
include(GoogleTest)
gtest_discover_tests(${TEST_RUNNER})
endif()

View File

@@ -0,0 +1,23 @@
#ifndef FLUTTER_PLUGIN_KEYPRESS_SIMULATOR_WINDOWS_PLUGIN_C_API_H_
#define FLUTTER_PLUGIN_KEYPRESS_SIMULATOR_WINDOWS_PLUGIN_C_API_H_
#include <flutter_plugin_registrar.h>
#ifdef FLUTTER_PLUGIN_IMPL
#define FLUTTER_PLUGIN_EXPORT __declspec(dllexport)
#else
#define FLUTTER_PLUGIN_EXPORT __declspec(dllimport)
#endif
#if defined(__cplusplus)
extern "C" {
#endif
FLUTTER_PLUGIN_EXPORT void KeypressSimulatorWindowsPluginCApiRegisterWithRegistrar(
FlutterDesktopPluginRegistrarRef registrar);
#if defined(__cplusplus)
} // extern "C"
#endif
#endif // FLUTTER_PLUGIN_KEYPRESS_SIMULATOR_WINDOWS_PLUGIN_C_API_H_

View File

@@ -0,0 +1,98 @@
#include "keypress_simulator_windows_plugin.h"
// This must be included before many other Windows headers.
#include <windows.h>
#include <flutter/method_channel.h>
#include <flutter/plugin_registrar_windows.h>
#include <flutter/standard_method_codec.h>
#include <memory>
#include <sstream>
using flutter::EncodableList;
using flutter::EncodableMap;
using flutter::EncodableValue;
namespace keypress_simulator_windows {
// static
void KeypressSimulatorWindowsPlugin::RegisterWithRegistrar(
flutter::PluginRegistrarWindows* registrar) {
auto channel =
std::make_unique<flutter::MethodChannel<flutter::EncodableValue>>(
registrar->messenger(), "dev.leanflutter.plugins/keypress_simulator",
&flutter::StandardMethodCodec::GetInstance());
auto plugin = std::make_unique<KeypressSimulatorWindowsPlugin>();
channel->SetMethodCallHandler(
[plugin_pointer = plugin.get()](const auto& call, auto result) {
plugin_pointer->HandleMethodCall(call, std::move(result));
});
registrar->AddPlugin(std::move(plugin));
}
KeypressSimulatorWindowsPlugin::KeypressSimulatorWindowsPlugin() {}
KeypressSimulatorWindowsPlugin::~KeypressSimulatorWindowsPlugin() {}
void KeypressSimulatorWindowsPlugin::SimulateKeyPress(
const flutter::MethodCall<flutter::EncodableValue>& method_call,
std::unique_ptr<flutter::MethodResult<flutter::EncodableValue>> result) {
const EncodableMap& args = std::get<EncodableMap>(*method_call.arguments());
UINT keyCode = std::get<int>(args.at(EncodableValue("keyCode")));
std::vector<std::string> modifiers;
bool keyDown = std::get<bool>(args.at(EncodableValue("keyDown")));
EncodableList key_modifier_list =
std::get<EncodableList>(args.at(EncodableValue("modifiers")));
for (flutter::EncodableValue key_modifier_value : key_modifier_list) {
std::string key_modifier = std::get<std::string>(key_modifier_value);
modifiers.push_back(key_modifier);
}
INPUT input[6];
for (int32_t i = 0; i < modifiers.size(); i++) {
if (modifiers[i].compare("shiftModifier") == 0) {
input[i].ki.wVk = VK_SHIFT;
} else if (modifiers[i].compare("controlModifier") == 0) {
input[i].ki.wVk = VK_CONTROL;
} else if (modifiers[i].compare("altModifier") == 0) {
input[i].ki.wVk = VK_MENU;
} else if (modifiers[i].compare("metaModifier") == 0) {
input[i].ki.wVk = VK_LWIN;
}
input[i].ki.dwFlags = keyDown ? 0 : KEYEVENTF_KEYUP;
input[i].type = INPUT_KEYBOARD;
}
/*int keyIndex = static_cast<int>(modifiers.size());
input[keyIndex].ki.wVk = static_cast<WORD>(keyCode);
input[keyIndex].ki.dwFlags = keyDown ? 0 : KEYEVENTF_KEYUP;
input[keyIndex].type = INPUT_KEYBOARD;*/
// Send key sequence to system
//SendInput(static_cast<UINT>(std::size(input)), input, sizeof(INPUT));
BYTE byteValue = static_cast<BYTE>(keyCode);
keybd_event(byteValue, 0x45, keyDown ? 0 : KEYEVENTF_KEYUP, 0);
result->Success(flutter::EncodableValue(true));
}
void KeypressSimulatorWindowsPlugin::HandleMethodCall(
const flutter::MethodCall<flutter::EncodableValue>& method_call,
std::unique_ptr<flutter::MethodResult<flutter::EncodableValue>> result) {
if (method_call.method_name().compare("simulateKeyPress") == 0) {
SimulateKeyPress(method_call, std::move(result));
} else {
result->NotImplemented();
}
}
} // namespace keypress_simulator_windows

View File

@@ -0,0 +1,37 @@
#ifndef FLUTTER_PLUGIN_KEYPRESS_SIMULATOR_WINDOWS_PLUGIN_H_
#define FLUTTER_PLUGIN_KEYPRESS_SIMULATOR_WINDOWS_PLUGIN_H_
#include <flutter/method_channel.h>
#include <flutter/plugin_registrar_windows.h>
#include <memory>
namespace keypress_simulator_windows {
class KeypressSimulatorWindowsPlugin : public flutter::Plugin {
public:
static void RegisterWithRegistrar(flutter::PluginRegistrarWindows* registrar);
KeypressSimulatorWindowsPlugin();
virtual ~KeypressSimulatorWindowsPlugin();
// Disallow copy and assign.
KeypressSimulatorWindowsPlugin(const KeypressSimulatorWindowsPlugin&) =
delete;
KeypressSimulatorWindowsPlugin& operator=(
const KeypressSimulatorWindowsPlugin&) = delete;
void KeypressSimulatorWindowsPlugin::SimulateKeyPress(
const flutter::MethodCall<flutter::EncodableValue>& method_call,
std::unique_ptr<flutter::MethodResult<flutter::EncodableValue>> result);
// Called when a method is called on this plugin's channel from Dart.
void HandleMethodCall(
const flutter::MethodCall<flutter::EncodableValue>& method_call,
std::unique_ptr<flutter::MethodResult<flutter::EncodableValue>> result);
};
} // namespace keypress_simulator_windows
#endif // FLUTTER_PLUGIN_KEYPRESS_SIMULATOR_WINDOWS_PLUGIN_H_

View File

@@ -0,0 +1,12 @@
#include "include/keypress_simulator_windows/keypress_simulator_windows_plugin_c_api.h"
#include <flutter/plugin_registrar_windows.h>
#include "keypress_simulator_windows_plugin.h"
void KeypressSimulatorWindowsPluginCApiRegisterWithRegistrar(
FlutterDesktopPluginRegistrarRef registrar) {
keypress_simulator_windows::KeypressSimulatorWindowsPlugin::RegisterWithRegistrar(
flutter::PluginRegistrarManager::GetInstance()
->GetRegistrar<flutter::PluginRegistrarWindows>(registrar));
}

View File

@@ -0,0 +1,43 @@
#include <flutter/method_call.h>
#include <flutter/method_result_functions.h>
#include <flutter/standard_method_codec.h>
#include <gtest/gtest.h>
#include <windows.h>
#include <memory>
#include <string>
#include <variant>
#include "keypress_simulator_windows_plugin.h"
namespace keypress_simulator_windows {
namespace test {
namespace {
using flutter::EncodableMap;
using flutter::EncodableValue;
using flutter::MethodCall;
using flutter::MethodResultFunctions;
} // namespace
TEST(KeypressSimulatorWindowsPlugin, GetPlatformVersion) {
KeypressSimulatorWindowsPlugin plugin;
// Save the reply value from the success callback.
std::string result_string;
plugin.HandleMethodCall(
MethodCall("getPlatformVersion", std::make_unique<EncodableValue>()),
std::make_unique<MethodResultFunctions<>>(
[&result_string](const EncodableValue* result) {
result_string = std::get<std::string>(*result);
},
nullptr, nullptr));
// Since the exact string varies by host, just ensure that it's a string
// with the expected format.
EXPECT_TRUE(result_string.rfind("Windows ", 0) == 0);
}
} // namespace test
} // namespace keypress_simulator_windows

View File

@@ -0,0 +1,9 @@
name: keypress_simulator_workspace
homepage: https://github.com/leanflutter/keypress_simulator
publish_to: none
environment:
sdk: ">=3.0.0 <4.0.0"
dev_dependencies:
melos: ^3.1.0

View File

@@ -1,13 +1,11 @@
import 'dart:typed_data';
import 'package:flutter_blue_plus/flutter_blue_plus.dart';
class BleUuid {
static final ZWIFT_CUSTOM_SERVICE_UUID = Guid("00000001-19CA-4651-86E5-FA29DCDD09D1");
static final ZWIFT_RIDE_CUSTOM_SERVICE_UUID = Guid("0000fc82-0000-1000-8000-00805f9b34fb");
static final ZWIFT_ASYNC_CHARACTERISTIC_UUID = Guid("00000002-19CA-4651-86E5-FA29DCDD09D1");
static final ZWIFT_SYNC_RX_CHARACTERISTIC_UUID = Guid("00000003-19CA-4651-86E5-FA29DCDD09D1");
static final ZWIFT_SYNC_TX_CHARACTERISTIC_UUID = Guid("00000004-19CA-4651-86E5-FA29DCDD09D1");
static final ZWIFT_CUSTOM_SERVICE_UUID = "00000001-19CA-4651-86E5-FA29DCDD09D1".toLowerCase();
static final ZWIFT_RIDE_CUSTOM_SERVICE_UUID = "0000fc82-0000-1000-8000-00805f9b34fb".toLowerCase();
static final ZWIFT_ASYNC_CHARACTERISTIC_UUID = "00000002-19CA-4651-86E5-FA29DCDD09D1".toLowerCase();
static final ZWIFT_SYNC_RX_CHARACTERISTIC_UUID = "00000003-19CA-4651-86E5-FA29DCDD09D1".toLowerCase();
static final ZWIFT_SYNC_TX_CHARACTERISTIC_UUID = "00000004-19CA-4651-86E5-FA29DCDD09D1".toLowerCase();
}
class Constants {
@@ -17,6 +15,10 @@ class Constants {
static const RC1_LEFT_SIDE = 0x03;
static const RC1_RIGHT_SIDE = 0x02;
// Zwift Ride
static const RIDE_RIGHT_SIDE = 0x07;
static const RIDE_LEFT_SIDE = 0x08;
// Zwift Click = BC1
static const BC1 = 0x09;
@@ -35,7 +37,7 @@ class Constants {
// not figured out the protobuf type this really is, the content is just two varints.
static const int CLICK_NOTIFICATION_MESSAGE_TYPE = 55;
static const int PLAY_NOTIFICATION_MESSAGE_TYPE = 7;
static const int RIDE_NOTIFICATION_MESSAGE_TYPE = 35;
static const int RIDE_NOTIFICATION_MESSAGE_TYPE = 35; // 0x23
// see this if connected to Core then Zwift connects to it. just one byte
static const DISCONNECT_MESSAGE_TYPE = 0xFE;
@@ -43,9 +45,10 @@ class Constants {
enum DeviceType {
click,
ride,
playLeft,
playRight;
playRight,
rideRight,
rideLeft;
@override
String toString() {
@@ -61,6 +64,10 @@ enum DeviceType {
return DeviceType.playLeft;
case Constants.RC1_RIGHT_SIDE:
return DeviceType.playRight;
case Constants.RIDE_RIGHT_SIDE:
return DeviceType.rideRight;
case Constants.RIDE_LEFT_SIDE:
return DeviceType.rideLeft;
}
return null;
}

View File

@@ -0,0 +1,166 @@
import 'dart:async';
import 'dart:io';
import 'package:dartx/dartx.dart';
import 'package:flutter/foundation.dart';
import 'package:swift_control/main.dart';
import 'package:swift_control/utils/requirements/android.dart';
import 'package:universal_ble/universal_ble.dart';
import '../bluetooth/ble.dart';
import 'devices/base_device.dart';
import 'messages/notification.dart';
class Connection {
final devices = <BaseDevice>[];
var androidNotificationsSetup = false;
final _connectionQueue = <BaseDevice>[];
var _handlingConnectionQueue = false;
final Map<BaseDevice, StreamSubscription<BaseNotification>> _streamSubscriptions = {};
final StreamController<BaseNotification> _actionStreams = StreamController<BaseNotification>.broadcast();
Stream<BaseNotification> get actionStream => _actionStreams.stream;
final Map<BaseDevice, StreamSubscription<BleConnectionUpdate>> _connectionSubscriptions = {};
final StreamController<BaseDevice> _connectionStreams = StreamController<BaseDevice>.broadcast();
Stream<BaseDevice> get connectionStream => _connectionStreams.stream;
final _lastScanResult = <BleDevice>[];
final ValueNotifier<bool> hasDevices = ValueNotifier(false);
final ValueNotifier<bool> isScanning = ValueNotifier(false);
void initialize() {
UniversalBle.onScanResult = (result) {
if (_lastScanResult.none((e) => e.deviceId == result.deviceId)) {
_lastScanResult.add(result);
final scanResult = BaseDevice.fromScanResult(result);
_actionStreams.add(
LogNotification('Found new device: ${result.name ?? scanResult?.runtimeType ?? result.deviceId}'),
);
if (scanResult != null) {
_addDevices([scanResult]);
}
}
};
UniversalBle.onValueChange = (deviceId, characteristicUuid, value) {
final device = devices.firstOrNullWhere((e) => e.device.deviceId == deviceId);
if (device == null) {
_actionStreams.add(LogNotification('Device not found: $deviceId'));
return;
} else {
device.processCharacteristic(characteristicUuid, value);
}
};
}
Future<void> performScanning() async {
isScanning.value = true;
// does not work on web, may not work on Windows
if (!kIsWeb && !Platform.isWindows) {
UniversalBle.getSystemDevices(
withServices: [BleUuid.ZWIFT_CUSTOM_SERVICE_UUID, BleUuid.ZWIFT_RIDE_CUSTOM_SERVICE_UUID],
).then((devices) async {
final baseDevices = devices.mapNotNull(BaseDevice.fromScanResult).toList();
if (baseDevices.isNotEmpty) {
_addDevices(baseDevices);
}
});
}
await UniversalBle.startScan(
scanFilter: ScanFilter(withServices: [BleUuid.ZWIFT_CUSTOM_SERVICE_UUID, BleUuid.ZWIFT_RIDE_CUSTOM_SERVICE_UUID]),
platformConfig: PlatformConfig(web: WebOptions(optionalServices: [BleUuid.ZWIFT_CUSTOM_SERVICE_UUID])),
);
Future.delayed(Duration(seconds: 30)).then((_) {
if (isScanning.value) {
UniversalBle.stopScan();
isScanning.value = false;
}
});
}
void _addDevices(List<BaseDevice> dev) {
final newDevices = dev.where((device) => !devices.contains(device)).toList();
devices.addAll(newDevices);
_connectionQueue.addAll(newDevices);
_handleConnectionQueue();
hasDevices.value = devices.isNotEmpty;
if (devices.isNotEmpty && !androidNotificationsSetup && !kIsWeb && Platform.isAndroid) {
androidNotificationsSetup = true;
actionHandler.init(null);
NotificationRequirement.setup().catchError((e) {
_actionStreams.add(LogNotification(e.toString()));
});
}
}
void _handleConnectionQueue() {
// windows apparently has issues when connecting to multiple devices at once, so don't
if (_connectionQueue.isNotEmpty && !_handlingConnectionQueue) {
_handlingConnectionQueue = true;
final device = _connectionQueue.removeAt(0);
_actionStreams.add(LogNotification('Connecting to: ${device.device.name ?? device.runtimeType}'));
_connect(device)
.then((_) {
_handlingConnectionQueue = false;
_actionStreams.add(LogNotification('Connection finished: ${device.device.name ?? device.runtimeType}'));
if (_connectionQueue.isNotEmpty) {
_handleConnectionQueue();
}
})
.catchError((e) {
_handlingConnectionQueue = false;
_actionStreams.add(LogNotification('Connection failed: ${device.device.name ?? device.runtimeType} - $e'));
if (_connectionQueue.isNotEmpty) {
_handleConnectionQueue();
}
});
}
}
Future<void> _connect(BaseDevice bleDevice) async {
try {
final actionSubscription = bleDevice.actionStream.listen((data) {
_actionStreams.add(data);
});
final connectionStateSubscription = UniversalBle.connectionStream(bleDevice.device.deviceId).listen((
state,
) async {
bleDevice.isConnected = state.isConnected;
_connectionStreams.add(bleDevice);
});
_connectionSubscriptions[bleDevice] = connectionStateSubscription;
await bleDevice.connect();
_streamSubscriptions[bleDevice] = actionSubscription;
} catch (e, backtrace) {
_actionStreams.add(LogNotification(e.toString()));
if (kDebugMode) {
print(e);
print("backtrace: $backtrace");
}
rethrow;
}
}
void reset() {
UniversalBle.stopScan();
isScanning.value = false;
for (var device in devices) {
_streamSubscriptions[device]?.cancel();
_streamSubscriptions.remove(device);
_connectionSubscriptions[device]?.cancel();
_connectionSubscriptions.remove(device);
UniversalBle.disconnect(device.device.deviceId);
}
_lastScanResult.clear();
hasDevices.value = false;
devices.clear();
}
}

View File

@@ -0,0 +1,223 @@
import 'dart:async';
import 'dart:io';
import 'package:dartx/dartx.dart';
import 'package:flutter/foundation.dart';
import 'package:swift_control/bluetooth/ble.dart';
import 'package:swift_control/bluetooth/devices/zwift_click.dart';
import 'package:swift_control/bluetooth/devices/zwift_play.dart';
import 'package:swift_control/bluetooth/devices/zwift_ride.dart';
import 'package:swift_control/utils/crypto/local_key_provider.dart';
import 'package:swift_control/utils/crypto/zap_crypto.dart';
import 'package:universal_ble/universal_ble.dart';
import '../../utils/crypto/encryption_utils.dart';
import '../messages/notification.dart';
abstract class BaseDevice {
final BleDevice scanResult;
BaseDevice(this.scanResult);
final zapEncryption = ZapCrypto(LocalKeyProvider());
bool isConnected = false;
bool supportsEncryption = true;
List<int> get startCommand => Constants.RIDE_ON + Constants.RESPONSE_START_CLICK;
String get customServiceId => BleUuid.ZWIFT_CUSTOM_SERVICE_UUID;
static BaseDevice? fromScanResult(BleDevice scanResult) {
// Use the name first as the "System Devices" and Web (android sometimes Windows) don't have manufacturer data
final device = switch (scanResult.name) {
//'Zwift Ride' => ZwiftRide(scanResult), special case for Zwift Ride: we must only connect to the left controller
// https://www.makinolo.com/blog/2024/07/26/zwift-ride-protocol/
'Zwift Play' => ZwiftPlay(scanResult),
'Zwift Click' => ZwiftClick(scanResult),
_ => null,
};
if (device != null) {
return device;
} else {
// otherwise use the manufacturer data to identify the device
final manufacturerData = scanResult.manufacturerDataList;
final data = manufacturerData.firstOrNullWhere((e) => e.companyId == Constants.ZWIFT_MANUFACTURER_ID)?.payload;
if (data == null || data.isEmpty) {
return null;
}
final type = DeviceType.fromManufacturerData(data.first);
return switch (type) {
DeviceType.click => ZwiftClick(scanResult),
DeviceType.playRight => ZwiftPlay(scanResult),
DeviceType.playLeft => ZwiftPlay(scanResult),
//DeviceType.rideRight => ZwiftRide(scanResult), // see comment above
DeviceType.rideLeft => ZwiftRide(scanResult),
_ => null,
};
}
}
@override
bool operator ==(Object other) =>
identical(this, other) ||
other is BaseDevice && runtimeType == other.runtimeType && scanResult == other.scanResult;
@override
int get hashCode => scanResult.hashCode;
@override
String toString() {
return runtimeType.toString();
}
BleDevice get device => scanResult;
final StreamController<BaseNotification> actionStreamInternal = StreamController<BaseNotification>.broadcast();
Stream<BaseNotification> get actionStream => actionStreamInternal.stream;
Future<void> connect() async {
await UniversalBle.connect(device.deviceId);
if (!kIsWeb && Platform.isAndroid) {
//await UniversalBle.requestMtu(device.deviceId, 256);
}
final services = await UniversalBle.discoverServices(device.deviceId);
await _handleServices(services);
}
Future<void> _handleServices(List<BleService> services) async {
final customService = services.firstOrNullWhere((service) => service.uuid == customServiceId);
if (customService == null) {
throw Exception(
'Custom service $customServiceId not found for device $this ${device.name ?? device.rawName}.\nYou may need to update the firmware in Zwift Companion app.\nWe found: ${services.joinToString(transform: (s) => s.uuid)}',
);
}
final asyncCharacteristic = customService.characteristics.firstOrNullWhere(
(characteristic) => characteristic.uuid == BleUuid.ZWIFT_ASYNC_CHARACTERISTIC_UUID,
);
final syncTxCharacteristic = customService.characteristics.firstOrNullWhere(
(characteristic) => characteristic.uuid == BleUuid.ZWIFT_SYNC_TX_CHARACTERISTIC_UUID,
);
final syncRxCharacteristic = customService.characteristics.firstOrNullWhere(
(characteristic) => characteristic.uuid == BleUuid.ZWIFT_SYNC_RX_CHARACTERISTIC_UUID,
);
if (asyncCharacteristic == null || syncTxCharacteristic == null || syncRxCharacteristic == null) {
throw Exception('Characteristics not found');
}
await UniversalBle.setNotifiable(
device.deviceId,
customService.uuid,
asyncCharacteristic.uuid,
BleInputProperty.notification,
);
await UniversalBle.setNotifiable(
device.deviceId,
customService.uuid,
syncTxCharacteristic.uuid,
BleInputProperty.indication,
);
await _setupHandshake(syncRxCharacteristic);
}
Future<void> _setupHandshake(BleCharacteristic syncRxCharacteristic) async {
if (supportsEncryption) {
await UniversalBle.writeValue(
device.deviceId,
customServiceId,
syncRxCharacteristic.uuid,
Uint8List.fromList([
...Constants.RIDE_ON,
...Constants.REQUEST_START,
...zapEncryption.localKeyProvider.getPublicKeyBytes(),
]),
BleOutputProperty.withoutResponse,
);
} else {
await UniversalBle.writeValue(
device.deviceId,
customServiceId,
syncRxCharacteristic.uuid,
Constants.RIDE_ON,
BleOutputProperty.withoutResponse,
);
}
}
void processCharacteristic(String characteristic, Uint8List bytes) {
if (kDebugMode && false) {
print('Received $characteristic: ${bytes.map((e) => e.toRadixString(16).padLeft(2, '0')).join(' ')}');
print('Received $characteristic: ${String.fromCharCodes(bytes)}');
}
if (bytes.isEmpty) {
return;
}
try {
if (bytes.startsWith(startCommand)) {
_processDevicePublicKeyResponse(bytes);
} else if (bytes.startsWith(Constants.RIDE_ON)) {
//print("Empty RideOn response - unencrypted mode");
} else if (!supportsEncryption || (bytes.length > Int32List.bytesPerElement + EncryptionUtils.MAC_LENGTH)) {
_processData(bytes);
} else if (bytes[0] == Constants.DISCONNECT_MESSAGE_TYPE) {
//print("Disconnect message");
} else {
//print("Unprocessed - Data Type: ${bytes.map((e) => e.toRadixString(16).padLeft(2, '0')).join(' ')}");
}
} catch (e, stackTrace) {
print("Error processing data: $e");
print("Stack Trace: $stackTrace");
actionStreamInternal.add(LogNotification(e.toString()));
}
}
void _processDevicePublicKeyResponse(Uint8List bytes) {
final devicePublicKeyBytes = bytes.sublist(Constants.RIDE_ON.length + Constants.RESPONSE_START_CLICK.length);
zapEncryption.initialise(devicePublicKeyBytes);
if (kDebugMode) {
print("Device Public Key - ${devicePublicKeyBytes.map((e) => e.toRadixString(16).padLeft(2, '0')).join(' ')}");
}
}
void _processData(Uint8List bytes) {
int type;
Uint8List message;
if (supportsEncryption) {
final counter = bytes.sublist(0, 4); // Int.SIZE_BYTES is 4
final payload = bytes.sublist(4);
final data = zapEncryption.decrypt(counter, payload);
type = data[0];
message = data.sublist(1);
} else {
type = bytes[0];
message = bytes.sublist(1);
}
switch (type) {
case Constants.EMPTY_MESSAGE_TYPE:
//print("Empty Message"); // expected when nothing happening
break;
case Constants.BATTERY_LEVEL_TYPE:
//print("Battery level update: $message");
break;
case Constants.CLICK_NOTIFICATION_MESSAGE_TYPE:
case Constants.PLAY_NOTIFICATION_MESSAGE_TYPE:
case Constants.RIDE_NOTIFICATION_MESSAGE_TYPE: // untested
processClickNotification(message);
break;
}
}
void processClickNotification(Uint8List message);
}

View File

@@ -0,0 +1,26 @@
import 'package:flutter/foundation.dart';
import 'package:swift_control/bluetooth/devices/base_device.dart';
import 'package:swift_control/main.dart';
import '../messages/click_notification.dart';
class ZwiftClick extends BaseDevice {
ZwiftClick(super.scanResult);
ClickNotification? _lastClickNotification;
@override
void processClickNotification(Uint8List message) {
final ClickNotification clickNotification = ClickNotification(message);
if (_lastClickNotification == null || _lastClickNotification != clickNotification) {
_lastClickNotification = clickNotification;
actionStreamInternal.add(clickNotification);
if (clickNotification.buttonUp) {
actionHandler.increaseGear();
} else if (clickNotification.buttonDown) {
actionHandler.decreaseGear();
}
}
}
}

View File

@@ -0,0 +1,44 @@
import 'package:accessibility/accessibility.dart';
import 'package:flutter/foundation.dart';
import 'package:swift_control/bluetooth/devices/base_device.dart';
import 'package:swift_control/bluetooth/messages/play_notification.dart';
import '../../main.dart';
import '../ble.dart';
class ZwiftPlay extends BaseDevice {
ZwiftPlay(super.scanResult);
PlayNotification? _lastControllerNotification;
@override
List<int> get startCommand => Constants.RIDE_ON + Constants.RESPONSE_START_PLAY;
@override
void processClickNotification(Uint8List message) {
final PlayNotification clickNotification = PlayNotification(message);
if (_lastControllerNotification == null || _lastControllerNotification != clickNotification) {
_lastControllerNotification = clickNotification;
actionStreamInternal.add(clickNotification);
if ((clickNotification.rightPad && clickNotification.buttonShift) ||
(clickNotification.rightPad && clickNotification.analogLR.abs() == 100)) {
actionHandler.increaseGear();
} else if ((!clickNotification.rightPad && clickNotification.buttonShift) ||
(!clickNotification.rightPad && clickNotification.analogLR.abs() == 100)) {
actionHandler.decreaseGear();
}
if (clickNotification.rightPad) {
if (clickNotification.buttonA) {
actionHandler.controlMedia(MediaAction.next);
} else if (clickNotification.buttonY) {
actionHandler.controlMedia(MediaAction.volumeUp);
} else if (clickNotification.buttonB) {
actionHandler.controlMedia(MediaAction.volumeDown);
} else if (clickNotification.buttonZ) {
actionHandler.controlMedia(MediaAction.playPause);
}
}
}
}
}

View File

@@ -0,0 +1,49 @@
import 'dart:typed_data';
import 'package:swift_control/bluetooth/devices/base_device.dart';
import 'package:swift_control/bluetooth/messages/ride_notification.dart';
import 'package:swift_control/main.dart';
import '../ble.dart';
class ZwiftRide extends BaseDevice {
ZwiftRide(super.scanResult);
@override
String get customServiceId => BleUuid.ZWIFT_RIDE_CUSTOM_SERVICE_UUID;
@override
bool get supportsEncryption => false;
RideNotification? _lastControllerNotification;
@override
void processClickNotification(Uint8List message) {
final RideNotification clickNotification = RideNotification(message);
if (_lastControllerNotification == null || _lastControllerNotification != clickNotification) {
_lastControllerNotification = clickNotification;
actionStreamInternal.add(clickNotification);
if (clickNotification.buttonShiftDownLeft ||
clickNotification.buttonShiftUpLeft ||
clickNotification.buttonOnOffLeft ||
clickNotification.buttonPowerUpLeft) {
actionHandler.decreaseGear();
} else if (clickNotification.buttonShiftUpRight ||
clickNotification.buttonShiftDownRight ||
clickNotification.buttonOnOffRight ||
clickNotification.buttonPowerUpRight) {
actionHandler.increaseGear();
}
/*if (clickNotification.buttonA) {
actionHandler.controlMedia(MediaAction.next);
} else if (clickNotification.buttonY) {
actionHandler.controlMedia(MediaAction.volumeUp);
} else if (clickNotification.buttonB) {
actionHandler.controlMedia(MediaAction.volumeDown);
} else if (clickNotification.buttonZ) {
actionHandler.controlMedia(MediaAction.playPause);
}*/
}
}
}

View File

@@ -1,19 +1,16 @@
import 'dart:typed_data';
import 'package:swift_control/utils/messages/notification.dart';
import '../../protocol/zwift.pb.dart';
import '../protocol/zwift.pb.dart';
import 'notification.dart';
class ClickNotification extends BaseNotification {
static const int BTN_PRESSED = 0;
bool buttonUp = false;
bool buttonDown = false;
ClickNotification(Uint8List message) {
final status = ClickKeyPadStatus.fromBuffer(message);
buttonUp = status.buttonPlus.value == BTN_PRESSED;
buttonDown = status.buttonMinus.value == BTN_PRESSED;
buttonUp = status.buttonPlus == PlayButtonStatus.ON;
buttonDown = status.buttonMinus == PlayButtonStatus.ON;
}
@override

View File

@@ -1,25 +1,22 @@
import 'dart:typed_data';
import 'package:swift_control/utils/messages/notification.dart';
import '../../protocol/zwift.pb.dart';
class ControllerNotification extends BaseNotification {
static const int BTN_PRESSED = 0;
import 'package:swift_control/bluetooth/messages/notification.dart';
import 'package:swift_control/bluetooth/protocol/zwift.pb.dart';
class PlayNotification extends BaseNotification {
late bool rightPad, buttonY, buttonZ, buttonA, buttonB, buttonOn, buttonShift;
late int analogLR, analogUD;
ControllerNotification(Uint8List message) {
PlayNotification(Uint8List message) {
final status = PlayKeyPadStatus.fromBuffer(message);
rightPad = status.rightPad.value == BTN_PRESSED;
buttonY = status.buttonYUp.value == BTN_PRESSED;
buttonZ = status.buttonZLeft.value == BTN_PRESSED;
buttonA = status.buttonARight.value == BTN_PRESSED;
buttonB = status.buttonBDown.value == BTN_PRESSED;
buttonOn = status.buttonOn.value == BTN_PRESSED;
buttonShift = status.buttonShift.value == BTN_PRESSED;
rightPad = status.rightPad == PlayButtonStatus.ON;
buttonY = status.buttonYUp == PlayButtonStatus.ON;
buttonZ = status.buttonZLeft == PlayButtonStatus.ON;
buttonA = status.buttonARight == PlayButtonStatus.ON;
buttonB = status.buttonBDown == PlayButtonStatus.ON;
buttonOn = status.buttonOn == PlayButtonStatus.ON;
buttonShift = status.buttonShift == PlayButtonStatus.ON;
analogLR = status.analogLR;
analogUD = status.analogUD;
}
@@ -41,7 +38,7 @@ class ControllerNotification extends BaseNotification {
@override
bool operator ==(Object other) =>
identical(this, other) ||
other is ControllerNotification &&
other is PlayNotification &&
runtimeType == other.runtimeType &&
rightPad == other.rightPad &&
buttonY == other.buttonY &&

View File

@@ -0,0 +1,140 @@
import 'dart:typed_data';
import 'package:swift_control/bluetooth/messages/notification.dart';
import 'package:swift_control/bluetooth/protocol/zwift.pb.dart';
enum _RideButtonMask {
LEFT_BTN(0x00001),
UP_BTN(0x00002),
RIGHT_BTN(0x00004),
DOWN_BTN(0x00008),
A_BTN(0x00010),
B_BTN(0x00020),
Y_BTN(0x00040),
Z_BTN(0x00080),
SHFT_UP_L_BTN(0x00100),
SHFT_DN_L_BTN(0x00200),
SHFT_UP_R_BTN(0x01000),
SHFT_DN_R_BTN(0x02000),
POWERUP_L_BTN(0x00400),
POWERUP_R_BTN(0x04000),
ONOFF_L_BTN(0x00800),
ONOFF_R_BTN(0x08000);
final int mask;
const _RideButtonMask(this.mask);
}
class RideNotification extends BaseNotification {
static const int BTN_PRESSED = 0;
late bool buttonLeft, buttonRight, buttonUp, buttonDown;
late bool buttonA, buttonB, buttonY, buttonZ;
late bool buttonShiftUpLeft, buttonShiftDownLeft;
late bool buttonShiftUpRight, buttonShiftDownRight;
late bool buttonPowerUpLeft, buttonPowerUpRight;
late bool buttonOnOffLeft, buttonOnOffRight;
int analogLR = 0, analogUD = 0;
RideNotification(Uint8List message) {
final status = RideKeyPadStatus.fromBuffer(message);
buttonLeft = status.buttonMap & _RideButtonMask.LEFT_BTN.mask == BTN_PRESSED;
buttonRight = status.buttonMap & _RideButtonMask.RIGHT_BTN.mask == BTN_PRESSED;
buttonUp = status.buttonMap & _RideButtonMask.UP_BTN.mask == BTN_PRESSED;
buttonDown = status.buttonMap & _RideButtonMask.DOWN_BTN.mask == BTN_PRESSED;
buttonA = status.buttonMap & _RideButtonMask.A_BTN.mask == BTN_PRESSED;
buttonB = status.buttonMap & _RideButtonMask.B_BTN.mask == BTN_PRESSED;
buttonY = status.buttonMap & _RideButtonMask.Y_BTN.mask == BTN_PRESSED;
buttonZ = status.buttonMap & _RideButtonMask.Z_BTN.mask == BTN_PRESSED;
buttonShiftUpLeft = status.buttonMap & _RideButtonMask.SHFT_UP_L_BTN.mask == BTN_PRESSED;
buttonShiftDownLeft = status.buttonMap & _RideButtonMask.SHFT_DN_L_BTN.mask == BTN_PRESSED;
buttonShiftUpRight = status.buttonMap & _RideButtonMask.SHFT_UP_R_BTN.mask == BTN_PRESSED;
buttonShiftDownRight = status.buttonMap & _RideButtonMask.SHFT_DN_R_BTN.mask == BTN_PRESSED;
buttonPowerUpLeft = status.buttonMap & _RideButtonMask.POWERUP_L_BTN.mask == BTN_PRESSED;
buttonPowerUpRight = status.buttonMap & _RideButtonMask.POWERUP_R_BTN.mask == BTN_PRESSED;
buttonOnOffLeft = status.buttonMap & _RideButtonMask.ONOFF_L_BTN.mask == BTN_PRESSED;
buttonOnOffRight = status.buttonMap & _RideButtonMask.ONOFF_R_BTN.mask == BTN_PRESSED;
for (final analogue in status.analogButtons.groupStatus) {
if (analogue.location == RideAnalogLocation.LEFT || analogue.location == RideAnalogLocation.RIGHT) {
analogLR = analogue.analogValue;
} else if (analogue.location == RideAnalogLocation.DOWN || analogue.location == RideAnalogLocation.UP) {
analogUD = analogue.analogValue;
}
}
}
@override
String toString() {
final allTrueParameters = [
if (buttonLeft) 'buttonLeft',
if (buttonRight) 'buttonRight',
if (buttonUp) 'buttonUp',
if (buttonDown) 'buttonDown',
if (buttonA) 'buttonA',
if (buttonB) 'buttonB',
if (buttonY) 'buttonY',
if (buttonZ) 'buttonZ',
if (buttonShiftUpLeft) 'buttonShiftUpLeft',
if (buttonShiftDownLeft) 'buttonShiftDownLeft',
if (buttonShiftUpRight) 'buttonShiftUpRight',
if (buttonShiftDownRight) 'buttonShiftDownRight',
if (buttonPowerUpLeft) 'buttonPowerUpLeft',
if (buttonPowerUpRight) 'buttonPowerUpRight',
if (buttonOnOffLeft) 'buttonOnOffLeft',
if (buttonOnOffRight) 'buttonOnOffRight',
];
return '{$allTrueParameters, analogLR: $analogLR, analogUD: $analogUD}';
}
@override
bool operator ==(Object other) =>
identical(this, other) ||
other is RideNotification &&
runtimeType == other.runtimeType &&
buttonLeft == other.buttonLeft &&
buttonRight == other.buttonRight &&
buttonUp == other.buttonUp &&
buttonDown == other.buttonDown &&
buttonA == other.buttonA &&
buttonB == other.buttonB &&
buttonY == other.buttonY &&
buttonZ == other.buttonZ &&
buttonShiftUpLeft == other.buttonShiftUpLeft &&
buttonShiftDownLeft == other.buttonShiftDownLeft &&
buttonShiftUpRight == other.buttonShiftUpRight &&
buttonShiftDownRight == other.buttonShiftDownRight &&
buttonPowerUpLeft == other.buttonPowerUpLeft &&
buttonPowerUpRight == other.buttonPowerUpRight &&
buttonOnOffLeft == other.buttonOnOffLeft &&
buttonOnOffRight == other.buttonOnOffRight &&
analogLR == other.analogLR &&
analogUD == other.analogUD;
@override
int get hashCode =>
buttonLeft.hashCode ^
buttonRight.hashCode ^
buttonUp.hashCode ^
buttonDown.hashCode ^
buttonA.hashCode ^
buttonB.hashCode ^
buttonY.hashCode ^
buttonZ.hashCode ^
buttonShiftUpLeft.hashCode ^
buttonShiftDownLeft.hashCode ^
buttonShiftUpRight.hashCode ^
buttonShiftDownRight.hashCode ^
buttonPowerUpLeft.hashCode ^
buttonPowerUpRight.hashCode ^
buttonOnOffLeft.hashCode ^
buttonOnOffRight.hashCode ^
analogLR.hashCode ^
analogUD.hashCode;
}

View File

@@ -25,8 +25,8 @@ class PlayKeyPadStatus extends $pb.GeneratedMessage {
PlayButtonStatus? buttonZLeft,
PlayButtonStatus? buttonARight,
PlayButtonStatus? buttonBDown,
PlayButtonStatus? buttonOn,
PlayButtonStatus? buttonShift,
PlayButtonStatus? buttonOn,
$core.int? analogLR,
$core.int? analogUD,
}) {
@@ -46,12 +46,12 @@ class PlayKeyPadStatus extends $pb.GeneratedMessage {
if (buttonBDown != null) {
$result.buttonBDown = buttonBDown;
}
if (buttonOn != null) {
$result.buttonOn = buttonOn;
}
if (buttonShift != null) {
$result.buttonShift = buttonShift;
}
if (buttonOn != null) {
$result.buttonOn = buttonOn;
}
if (analogLR != null) {
$result.analogLR = analogLR;
}
@@ -70,8 +70,8 @@ class PlayKeyPadStatus extends $pb.GeneratedMessage {
..e<PlayButtonStatus>(3, _omitFieldNames ? '' : 'ButtonZLeft', $pb.PbFieldType.OE, protoName: 'Button_Z_Left', defaultOrMaker: PlayButtonStatus.ON, valueOf: PlayButtonStatus.valueOf, enumValues: PlayButtonStatus.values)
..e<PlayButtonStatus>(4, _omitFieldNames ? '' : 'ButtonARight', $pb.PbFieldType.OE, protoName: 'Button_A_Right', defaultOrMaker: PlayButtonStatus.ON, valueOf: PlayButtonStatus.valueOf, enumValues: PlayButtonStatus.values)
..e<PlayButtonStatus>(5, _omitFieldNames ? '' : 'ButtonBDown', $pb.PbFieldType.OE, protoName: 'Button_B_Down', defaultOrMaker: PlayButtonStatus.ON, valueOf: PlayButtonStatus.valueOf, enumValues: PlayButtonStatus.values)
..e<PlayButtonStatus>(6, _omitFieldNames ? '' : 'ButtonOn', $pb.PbFieldType.OE, protoName: 'Button_On', defaultOrMaker: PlayButtonStatus.ON, valueOf: PlayButtonStatus.valueOf, enumValues: PlayButtonStatus.values)
..e<PlayButtonStatus>(7, _omitFieldNames ? '' : 'ButtonShift', $pb.PbFieldType.OE, protoName: 'Button_Shift', defaultOrMaker: PlayButtonStatus.ON, valueOf: PlayButtonStatus.valueOf, enumValues: PlayButtonStatus.values)
..e<PlayButtonStatus>(6, _omitFieldNames ? '' : 'ButtonShift', $pb.PbFieldType.OE, protoName: 'Button_Shift', defaultOrMaker: PlayButtonStatus.ON, valueOf: PlayButtonStatus.valueOf, enumValues: PlayButtonStatus.values)
..e<PlayButtonStatus>(7, _omitFieldNames ? '' : 'ButtonOn', $pb.PbFieldType.OE, protoName: 'Button_On', defaultOrMaker: PlayButtonStatus.ON, valueOf: PlayButtonStatus.valueOf, enumValues: PlayButtonStatus.values)
..a<$core.int>(8, _omitFieldNames ? '' : 'AnalogLR', $pb.PbFieldType.OS3, protoName: 'Analog_LR')
..a<$core.int>(9, _omitFieldNames ? '' : 'AnalogUD', $pb.PbFieldType.OS3, protoName: 'Analog_UD')
..hasRequiredFields = false
@@ -144,22 +144,22 @@ class PlayKeyPadStatus extends $pb.GeneratedMessage {
void clearButtonBDown() => clearField(5);
@$pb.TagNumber(6)
PlayButtonStatus get buttonOn => $_getN(5);
PlayButtonStatus get buttonShift => $_getN(5);
@$pb.TagNumber(6)
set buttonOn(PlayButtonStatus v) { setField(6, v); }
set buttonShift(PlayButtonStatus v) { setField(6, v); }
@$pb.TagNumber(6)
$core.bool hasButtonOn() => $_has(5);
$core.bool hasButtonShift() => $_has(5);
@$pb.TagNumber(6)
void clearButtonOn() => clearField(6);
void clearButtonShift() => clearField(6);
@$pb.TagNumber(7)
PlayButtonStatus get buttonShift => $_getN(6);
PlayButtonStatus get buttonOn => $_getN(6);
@$pb.TagNumber(7)
set buttonShift(PlayButtonStatus v) { setField(7, v); }
set buttonOn(PlayButtonStatus v) { setField(7, v); }
@$pb.TagNumber(7)
$core.bool hasButtonShift() => $_has(6);
$core.bool hasButtonOn() => $_has(6);
@$pb.TagNumber(7)
void clearButtonShift() => clearField(7);
void clearButtonOn() => clearField(7);
@$pb.TagNumber(8)
$core.int get analogLR => $_getIZ(7);

View File

@@ -82,8 +82,8 @@ const PlayKeyPadStatus$json = {
{'1': 'Button_Z_Left', '3': 3, '4': 1, '5': 14, '6': '.de.jonasbark.PlayButtonStatus', '10': 'ButtonZLeft'},
{'1': 'Button_A_Right', '3': 4, '4': 1, '5': 14, '6': '.de.jonasbark.PlayButtonStatus', '10': 'ButtonARight'},
{'1': 'Button_B_Down', '3': 5, '4': 1, '5': 14, '6': '.de.jonasbark.PlayButtonStatus', '10': 'ButtonBDown'},
{'1': 'Button_On', '3': 6, '4': 1, '5': 14, '6': '.de.jonasbark.PlayButtonStatus', '10': 'ButtonOn'},
{'1': 'Button_Shift', '3': 7, '4': 1, '5': 14, '6': '.de.jonasbark.PlayButtonStatus', '10': 'ButtonShift'},
{'1': 'Button_Shift', '3': 6, '4': 1, '5': 14, '6': '.de.jonasbark.PlayButtonStatus', '10': 'ButtonShift'},
{'1': 'Button_On', '3': 7, '4': 1, '5': 14, '6': '.de.jonasbark.PlayButtonStatus', '10': 'ButtonOn'},
{'1': 'Analog_LR', '3': 8, '4': 1, '5': 17, '10': 'AnalogLR'},
{'1': 'Analog_UD', '3': 9, '4': 1, '5': 17, '10': 'AnalogUD'},
],
@@ -97,9 +97,9 @@ final $typed_data.Uint8List playKeyPadStatusDescriptor = $convert.base64Decode(
'4uZGUuam9uYXNiYXJrLlBsYXlCdXR0b25TdGF0dXNSC0J1dHRvblpMZWZ0EkQKDkJ1dHRvbl9B'
'X1JpZ2h0GAQgASgOMh4uZGUuam9uYXNiYXJrLlBsYXlCdXR0b25TdGF0dXNSDEJ1dHRvbkFSaW'
'dodBJCCg1CdXR0b25fQl9Eb3duGAUgASgOMh4uZGUuam9uYXNiYXJrLlBsYXlCdXR0b25TdGF0'
'dXNSC0J1dHRvbkJEb3duEjsKCUJ1dHRvbl9PbhgGIAEoDjIeLmRlLmpvbmFzYmFyay5QbGF5Qn'
'V0dG9uU3RhdHVzUghCdXR0b25PbhJBCgxCdXR0b25fU2hpZnQYByABKA4yHi5kZS5qb25hc2Jh'
'cmsuUGxheUJ1dHRvblN0YXR1c1ILQnV0dG9uU2hpZnQSGwoJQW5hbG9nX0xSGAggASgRUghBbm'
'dXNSC0J1dHRvbkJEb3duEkEKDEJ1dHRvbl9TaGlmdBgGIAEoDjIeLmRlLmpvbmFzYmFyay5QbG'
'F5QnV0dG9uU3RhdHVzUgtCdXR0b25TaGlmdBI7CglCdXR0b25fT24YByABKA4yHi5kZS5qb25h'
'c2JhcmsuUGxheUJ1dHRvblN0YXR1c1IIQnV0dG9uT24SGwoJQW5hbG9nX0xSGAggASgRUghBbm'
'Fsb2dMUhIbCglBbmFsb2dfVUQYCSABKBFSCEFuYWxvZ1VE');
@$core.Deprecated('Use playCommandParametersDescriptor instead')

View File

@@ -16,8 +16,8 @@ message PlayKeyPadStatus {
optional PlayButtonStatus Button_Z_Left = 3;
optional PlayButtonStatus Button_A_Right = 4;
optional PlayButtonStatus Button_B_Down = 5;
optional PlayButtonStatus Button_On = 6;
optional PlayButtonStatus Button_Shift = 7;
optional PlayButtonStatus Button_Shift = 6;
optional PlayButtonStatus Button_On = 7;
optional sint32 Analog_LR = 8;
optional sint32 Analog_UD = 9;
}

View File

@@ -1,18 +1,33 @@
import 'dart:io';
import 'package:accessibility/accessibility.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'package:swift_control/pages/requirements.dart';
import 'package:swift_control/theme.dart';
import 'package:swift_control/utils/connection.dart';
import 'package:swift_control/utils/actions/android.dart';
import 'package:swift_control/utils/actions/desktop.dart';
import 'package:swift_control/utils/settings/settings.dart';
import 'bluetooth/connection.dart';
import 'utils/actions/base_actions.dart';
final connection = Connection();
final actionHandler = ActionHandler();
late final BaseActions actionHandler;
final accessibilityHandler = Accessibility();
final flutterLocalNotificationsPlugin = FlutterLocalNotificationsPlugin();
final settings = Settings();
void main() {
if (kIsWeb) {
actionHandler = StubActions();
} else if (Platform.isAndroid) {
actionHandler = AndroidActions();
} else {
actionHandler = DesktopActions();
}
runApp(const SwiftPlayApp());
}
@@ -22,6 +37,7 @@ class SwiftPlayApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'SwiftControl',
theme: AppTheme.light,
darkTheme: AppTheme.dark,

View File

@@ -1,11 +1,16 @@
import 'dart:async';
import 'dart:io';
import 'package:dartx/dartx.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:swift_control/main.dart';
import 'package:swift_control/utils/devices/ble_device.dart';
import 'package:swift_control/pages/touch_area.dart';
import 'package:swift_control/widgets/logviewer.dart';
import 'package:swift_control/widgets/title.dart';
import '../utils/messages/notification.dart';
import '../bluetooth/devices/base_device.dart';
import '../widgets/menu.dart';
class DevicePage extends StatefulWidget {
const DevicePage({super.key});
@@ -15,24 +20,12 @@ class DevicePage extends StatefulWidget {
}
class _DevicePageState extends State<DevicePage> {
List<String> _actions = [];
late StreamSubscription<BleDevice> _connectionStateSubscription;
late StreamSubscription<BaseNotification> _actionSubscription;
late StreamSubscription<BaseDevice> _connectionStateSubscription;
@override
void initState() {
super.initState();
_actionSubscription = connection.actionStream.listen((data) {
if (mounted) {
setState(() {
_actions.add('${DateTime.now().toString().split(" ").last}: $data');
_actions = _actions.takeLast(30).toList();
});
}
});
_connectionStateSubscription = connection.connectionStream.listen((state) async {
setState(() {});
});
@@ -41,7 +34,6 @@ class _DevicePageState extends State<DevicePage> {
@override
void dispose() {
_connectionStateSubscription.cancel();
_actionSubscription.cancel();
super.dispose();
}
@@ -57,42 +49,52 @@ class _DevicePageState extends State<DevicePage> {
},
child: Scaffold(
appBar: AppBar(
title: Text('SwiftControl'),
actions: [
IconButton(
onPressed: () {
_actions.clear();
setState(() {});
},
icon: Icon(Icons.clear),
),
],
title: AppTitle(),
actions: buildMenuButtons(),
backgroundColor: Theme.of(context).colorScheme.inversePrimary,
),
body: Padding(
padding: const EdgeInsets.all(8.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
spacing: 10,
children: [
Text(
'Devices:\n${connection.devices.joinToString(separator: '\n', transform: (it) {
return "${it.device.platformName}: ${it.device.isConnected ? 'Connected' : 'Not connected'}";
return "${it.device.name ?? it.runtimeType}: ${it.isConnected ? 'Connected' : 'Not connected'}";
})}',
),
Divider(color: Theme.of(context).colorScheme.primary, height: 30),
Expanded(
child: ListView(
children:
_actions
.map(
(action) => Text(
action,
style: TextStyle(fontSize: 12, fontFeatures: [FontFeature.tabularFigures()]),
if (!kIsWeb && (Platform.isAndroid || kDebugMode)) ...[
ElevatedButton(
onPressed: () {
Navigator.of(context).push(
MaterialPageRoute(
builder:
(_) => TouchAreaSetupPage(
onSave: (gearUp, gearDown) {
final devicePixelRatio = MediaQuery.devicePixelRatioOf(context);
final convertedGearUp =
gearUp.translate(touchAreaSize / 2, touchAreaSize / 2) * devicePixelRatio;
final convertedGearDown =
gearDown.translate(touchAreaSize / 2, touchAreaSize / 2) * devicePixelRatio;
print("Gear Up Position: $gearUp - converted: $convertedGearUp");
print("Gear Down Position: $gearDown - converted: $convertedGearDown");
actionHandler.updateTouchPositions(convertedGearUp, convertedGearDown);
settings.updateTouchPositions(convertedGearUp, convertedGearDown);
},
),
)
.toList(),
),
);
},
child: Text('Customize touch areas (optional)'),
),
),
],
Expanded(child: LogViewer()),
],
),
),

View File

@@ -4,7 +4,10 @@ import 'package:dartx/dartx.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:swift_control/main.dart';
import 'package:swift_control/utils/requirements/multi.dart';
import 'package:swift_control/utils/requirements/platform.dart';
import 'package:swift_control/widgets/menu.dart';
import 'package:swift_control/widgets/title.dart';
import 'device.dart';
@@ -27,14 +30,16 @@ class _RequirementsPageState extends State<RequirementsPage> with WidgetsBinding
// call after first frame
WidgetsBinding.instance.addPostFrameCallback((_) {
if (!kIsWeb && Platform.isMacOS) {
// add more delay due tu CBManagerStateUnknown
Future.delayed(const Duration(seconds: 2), () {
settings.init().then((_) {
if (!kIsWeb && Platform.isMacOS) {
// add more delay due tu CBManagerStateUnknown
Future.delayed(const Duration(seconds: 2), () {
_reloadRequirements();
});
} else {
_reloadRequirements();
});
} else {
_reloadRequirements();
}
}
});
});
connection.hasDevices.addListener(() {
@@ -60,7 +65,11 @@ class _RequirementsPageState extends State<RequirementsPage> with WidgetsBinding
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('SwiftControl'), backgroundColor: Theme.of(context).colorScheme.inversePrimary),
appBar: AppBar(
title: AppTitle(),
backgroundColor: Theme.of(context).colorScheme.inversePrimary,
actions: buildMenuButtons(),
),
body:
_requirements.isEmpty
? Center(child: CircularProgressIndicator())
@@ -78,7 +87,7 @@ class _RequirementsPageState extends State<RequirementsPage> with WidgetsBinding
}
: null,
onStepTapped: (step) {
if (_requirements[step].status) {
if (_requirements[step].status && _requirements[step] is! KeymapRequirement) {
return;
}
final hasEarlierIncomplete = _requirements.indexWhere((req) => !req.status) < step;
@@ -95,16 +104,20 @@ class _RequirementsPageState extends State<RequirementsPage> with WidgetsBinding
.mapIndexed(
(index, req) => Step(
title: Text(req.name),
content:
(index == _currentStep
? req.build(context, () {
_reloadRequirements();
})
: null) ??
ElevatedButton(
onPressed: req.status ? null : () => _callRequirement(req),
child: Text(req.name),
),
content: Container(
padding: const EdgeInsets.symmetric(vertical: 16.0),
alignment: Alignment.centerLeft,
child:
(index == _currentStep
? req.build(context, () {
_reloadRequirements();
})
: null) ??
ElevatedButton(
onPressed: req.status ? null : () => _callRequirement(req),
child: Text(req.name),
),
),
state: req.status ? StepState.complete : StepState.indexed,
),
)

View File

@@ -1,12 +1,10 @@
import 'dart:async';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_blue_plus_windows/flutter_blue_plus_windows.dart';
import 'package:swift_control/main.dart';
import 'package:swift_control/utils/ble.dart';
import 'package:swift_control/widgets/small_progress_indicator.dart';
import '../widgets/logviewer.dart';
class ScanWidget extends StatefulWidget {
const ScanWidget({super.key});
@@ -15,73 +13,30 @@ class ScanWidget extends StatefulWidget {
}
class _ScanWidgetState extends State<ScanWidget> {
bool _isScanning = false;
late StreamSubscription<bool> _isScanningSubscription;
@override
void initState() {
super.initState();
connection.startScanning();
connection.initialize();
_isScanningSubscription = FlutterBluePlus.isScanning.listen((state) {
/*_isScanningSubscription = FlutterBluePlus.isScanning.listen((state) {
_isScanning = state;
if (mounted) {
setState(() {});
}
});
});*/
// after the first frame
WidgetsBinding.instance.addPostFrameCallback((_) {
onScanPressed();
// must be called from a button
if (!kIsWeb) {
Future.delayed(Duration(seconds: 1)).then((_) {
connection.performScanning();
});
}
});
}
@override
void dispose() {
_isScanningSubscription.cancel();
super.dispose();
}
Future onScanPressed() async {
try {
await FlutterBluePlus.startScan(
timeout: const Duration(seconds: 30),
withServices: [BleUuid.ZWIFT_CUSTOM_SERVICE_UUID, BleUuid.ZWIFT_RIDE_CUSTOM_SERVICE_UUID],
webOptionalServices: kIsWeb ? [BleUuid.ZWIFT_CUSTOM_SERVICE_UUID] : [],
);
} catch (e, backtrace) {
ScaffoldMessenger.of(
context,
).showSnackBar(SnackBar(content: Text('Error: $e'), duration: const Duration(seconds: 5)));
print(e);
print("backtrace: $backtrace");
}
if (mounted) {
setState(() {});
}
}
Future onStopPressed() async {
try {
FlutterBluePlus.stopScan();
} catch (e, backtrace) {
ScaffoldMessenger.of(
context,
).showSnackBar(SnackBar(content: Text('Error: $e'), duration: const Duration(seconds: 5)));
print(e);
print("backtrace: $backtrace");
}
}
Widget buildScanButton(BuildContext context) {
if (FlutterBluePlus.isScanningNow) {
return ElevatedButton(onPressed: onStopPressed, child: const Icon(Icons.stop));
} else {
return ElevatedButton(onPressed: onScanPressed, child: const Text("SCAN"));
}
}
@override
Widget build(BuildContext context) {
return Container(
@@ -89,7 +44,36 @@ class _ScanWidgetState extends State<ScanWidget> {
child: ListView(
padding: EdgeInsets.all(16),
shrinkWrap: true,
children: [if (_isScanning) SmallProgressIndicator() else buildScanButton(context)],
children: [
ValueListenableBuilder(
valueListenable: connection.isScanning,
builder: (context, isScanning, widget) {
if (isScanning) {
return Column(
spacing: 12,
children: [
Text(
'Scanning for devices... Make sure they are powered on and in range and not connected to another device.',
),
SmallProgressIndicator(),
],
);
} else {
return Row(
children: [
ElevatedButton(
onPressed: () {
connection.performScanning();
},
child: const Text("SCAN"),
),
],
);
}
},
),
if (kDebugMode) LogViewer(),
],
),
);
}

186
lib/pages/touch_area.dart Normal file
View File

@@ -0,0 +1,186 @@
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:image_picker/image_picker.dart';
import 'package:swift_control/main.dart';
final touchAreaSize = 32.0;
class TouchAreaSetupPage extends StatefulWidget {
final void Function(Offset gearUp, Offset gearDown) onSave;
const TouchAreaSetupPage({required this.onSave, super.key});
@override
State<TouchAreaSetupPage> createState() => _TouchAreaSetupPageState();
}
class _TouchAreaSetupPageState extends State<TouchAreaSetupPage> {
File? _backgroundImage;
Offset _gearUpPos = const Offset(200, 300);
Offset _gearDownPos = const Offset(100, 300);
Future<void> _pickScreenshot() async {
final picker = ImagePicker();
final result = await picker.pickImage(source: ImageSource.gallery);
if (result != null) {
setState(() {
_backgroundImage = File(result.path);
});
}
}
void _saveAndClose() {
widget.onSave(_gearUpPos, _gearDownPos);
Navigator.of(context).pop();
}
@override
void dispose() {
super.dispose();
// Exit full screen
SystemChrome.setEnabledSystemUIMode(SystemUiMode.manual, overlays: SystemUiOverlay.values);
}
@override
void initState() {
super.initState();
SystemChrome.setEnabledSystemUIMode(SystemUiMode.immersiveSticky, overlays: []);
WidgetsBinding.instance.addPostFrameCallback((_) {
final devicePixelRatio = MediaQuery.devicePixelRatioOf(context);
if (actionHandler.gearUpTouchPosition != null) {
_gearUpPos = actionHandler.gearUpTouchPosition!;
_gearUpPos = Offset(
_gearUpPos.dx / devicePixelRatio - touchAreaSize / 2,
_gearUpPos.dy / devicePixelRatio - touchAreaSize / 2,
);
}
if (actionHandler.gearDownTouchPosition != null) {
_gearDownPos = actionHandler.gearDownTouchPosition!;
_gearDownPos = Offset(
_gearDownPos.dx / devicePixelRatio - touchAreaSize / 2,
_gearDownPos.dy / devicePixelRatio - touchAreaSize / 2,
);
}
setState(() {});
});
}
Widget _buildDraggableArea({
required Offset position,
required void Function(Offset newPosition) onPositionChanged,
required Color color,
required String label,
}) {
return Positioned(
left: position.dx,
top: position.dy,
child: Draggable(
feedback: Material(color: Colors.transparent, child: _TouchDot(color: Colors.yellow, label: label)),
childWhenDragging: const SizedBox.shrink(),
onDraggableCanceled: (_, offset) {
setState(() => onPositionChanged(offset));
},
child: _TouchDot(color: color, label: label),
),
);
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Stack(
children: [
if (_backgroundImage != null)
Positioned.fill(child: Opacity(opacity: 0.5, child: Image.file(_backgroundImage!, fit: BoxFit.cover)))
else
Center(
child: Padding(
padding: const EdgeInsets.all(16.0),
child: Column(
mainAxisSize: MainAxisSize.min,
spacing: 8,
children: [
Text('''1. Create an in-game screenshot of your app (e.g. within MyWhoosh)
2. Load the screenshot with the button below
3. Make sure the app is in the correct orientation (portrait or landscape)
4. Drag the touch areas to the correct position where the gear up / down buttons are located
5. Save and close this screen'''),
ElevatedButton(
onPressed: () {
_pickScreenshot();
},
child: Text('Load in-game screenshot for placement'),
),
],
),
),
),
// Touch Areas
_buildDraggableArea(
position: _gearUpPos,
onPositionChanged: (newPos) => _gearUpPos = newPos,
color: Colors.red,
label: "Gear ↑",
),
_buildDraggableArea(
position: _gearDownPos,
onPositionChanged: (newPos) => _gearDownPos = newPos,
color: Colors.green,
label: "Gear ↓",
),
Positioned(
top: 40,
right: 170,
child: ElevatedButton.icon(
onPressed: () {
_gearDownPos = Offset(100, 300);
_gearUpPos = Offset(200, 300);
setState(() {});
},
label: const Icon(Icons.lock_reset),
),
),
Positioned(
top: 40,
right: 20,
child: ElevatedButton.icon(
onPressed: _saveAndClose,
icon: const Icon(Icons.save),
label: const Text("Save & Close"),
),
),
],
),
);
}
}
class _TouchDot extends StatelessWidget {
final Color color;
final String label;
const _TouchDot({required this.color, required this.label});
@override
Widget build(BuildContext context) {
return Column(
children: [
Container(
width: touchAreaSize,
height: touchAreaSize,
decoration: BoxDecoration(
color: color.withOpacity(0.6),
shape: BoxShape.circle,
border: Border.all(color: Colors.black, width: 2),
),
),
Text(label, style: TextStyle(color: Colors.black, fontSize: 12)),
],
);
}
}

View File

@@ -8,21 +8,33 @@ import 'package:swift_control/utils/keymap/keymap.dart';
class AndroidActions extends BaseActions {
static const MYWHOOSH_APP_PACKAGE = "com.mywhoosh.whooshgame";
static const TRAININGPEAKS_APP_PACKAGE = "com.indieVelo.client";
static const validPackageNames = [MYWHOOSH_APP_PACKAGE, TRAININGPEAKS_APP_PACKAGE];
WindowEvent? windowInfo;
Offset? _gearUpTouchPosition;
Offset? _gearDownTouchPosition;
@override
Offset? get gearUpTouchPosition => _gearUpTouchPosition;
@override
Offset? get gearDownTouchPosition => _gearDownTouchPosition;
@override
void init(Keymap? keymap) {
streamEvents().listen((windowEvent) {
windowInfo = windowEvent;
if (validPackageNames.contains(windowEvent.packageName)) {
windowInfo = windowEvent;
}
});
}
@override
void decreaseGear() {
if (windowInfo == null) {
throw Exception("Decrease gear: No window info");
} else {
if (_gearDownTouchPosition == null) {
if (windowInfo == null) {
throw Exception("Increasing gear: No window info");
}
final point = switch (windowInfo!.packageName) {
MYWHOOSH_APP_PACKAGE => Offset(windowInfo!.windowWidth * 0.80, windowInfo!.windowHeight * 0.94),
TRAININGPEAKS_APP_PACKAGE => Offset(windowInfo!.windowWidth / 2 * 1.15, windowInfo!.windowHeight * 0.74),
@@ -30,14 +42,17 @@ class AndroidActions extends BaseActions {
};
accessibilityHandler.performTouch(point.dx, point.dy);
} else {
accessibilityHandler.performTouch(_gearDownTouchPosition!.dx, _gearDownTouchPosition!.dy);
}
}
@override
void increaseGear() {
if (windowInfo == null) {
throw Exception("Increasing gear: No window info");
} else {
if (_gearUpTouchPosition == null) {
if (windowInfo == null) {
throw Exception("Increasing gear: No window info");
}
final point = switch (windowInfo!.packageName) {
MYWHOOSH_APP_PACKAGE => Offset(windowInfo!.windowWidth * 0.98, windowInfo!.windowHeight * 0.94),
TRAININGPEAKS_APP_PACKAGE => Offset(windowInfo!.windowWidth / 2 * 1.32, windowInfo!.windowHeight * 0.74),
@@ -45,6 +60,19 @@ class AndroidActions extends BaseActions {
};
accessibilityHandler.performTouch(point.dx, point.dy);
} else {
accessibilityHandler.performTouch(_gearUpTouchPosition!.dx, _gearUpTouchPosition!.dy);
}
}
@override
void controlMedia(MediaAction action) {
accessibilityHandler.controlMedia(action);
}
@override
void updateTouchPositions(Offset gearUp, Offset gearDown) {
_gearUpTouchPosition = gearUp;
_gearDownTouchPosition = gearDown;
}
}

View File

@@ -1,17 +1,23 @@
import 'dart:io';
import 'dart:ui';
import 'package:flutter/foundation.dart';
import 'package:accessibility/accessibility.dart';
import '../keymap/keymap.dart';
import 'android.dart';
import 'desktop.dart';
abstract class BaseActions {
Keymap? get keymap => null;
Offset? get gearUpTouchPosition => null;
Offset? get gearDownTouchPosition => null;
void init(Keymap? keymap) {}
void increaseGear();
void decreaseGear();
void controlMedia(MediaAction action) {
throw UnimplementedError();
}
void updateTouchPositions(Offset gearUp, Offset gearDown) {}
}
class StubActions extends BaseActions {
@@ -25,31 +31,3 @@ class StubActions extends BaseActions {
print('Increase gear');
}
}
class ActionHandler {
late BaseActions actions;
ActionHandler() {
if (kIsWeb) {
actions = StubActions();
} else if (Platform.isAndroid) {
actions = AndroidActions();
} else {
actions = DesktopActions();
}
}
Keymap? get keymap => actions.keymap;
void init(Keymap? keymap) {
actions.init(keymap);
}
void increaseGear() {
actions.increaseGear();
}
void decreaseGear() {
actions.decreaseGear();
}
}

View File

@@ -15,18 +15,20 @@ class DesktopActions extends BaseActions {
}
@override
void decreaseGear() {
Future<void> decreaseGear() async {
if (keymap == null) {
throw Exception('Keymap is not set');
}
keyPressSimulator.simulateKeyDown(_keymap!.decrease);
await keyPressSimulator.simulateKeyDown(_keymap!.decrease?.physicalKey);
await keyPressSimulator.simulateKeyUp(_keymap!.decrease?.physicalKey);
}
@override
void increaseGear() {
Future<void> increaseGear() async {
if (keymap == null) {
throw Exception('Keymap is not set');
}
keyPressSimulator.simulateKeyDown(_keymap!.increase);
await keyPressSimulator.simulateKeyDown(_keymap!.increase?.physicalKey);
await keyPressSimulator.simulateKeyUp(_keymap!.increase?.physicalKey);
}
}

View File

@@ -1,90 +0,0 @@
import 'dart:async';
import 'dart:io';
import 'package:dartx/dartx.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter_blue_plus/flutter_blue_plus.dart';
import 'package:swift_control/main.dart';
import 'package:swift_control/utils/devices/ble_device.dart';
import 'package:swift_control/utils/requirements/android.dart';
import 'messages/notification.dart';
class Connection {
final devices = <BleDevice>[];
var androidNotificationsSetup = false;
final Map<BleDevice, StreamSubscription<BaseNotification>> _streamSubscriptions = {};
final StreamController<BaseNotification> _actionStreams = StreamController<BaseNotification>.broadcast();
Stream<BaseNotification> get actionStream => _actionStreams.stream;
final Map<BleDevice, StreamSubscription<BluetoothConnectionState>> _connectionSubscriptions = {};
final StreamController<BleDevice> _connectionStreams = StreamController<BleDevice>.broadcast();
Stream<BleDevice> get connectionStream => _connectionStreams.stream;
final ValueNotifier<bool> hasDevices = ValueNotifier(false);
late StreamSubscription<List<ScanResult>> _scanResultsSubscription;
void startScanning() {
_scanResultsSubscription = FlutterBluePlus.scanResults.listen(
(results) {
final scanResults = results.mapNotNull(BleDevice.fromScanResult).toList();
_addDevices(scanResults);
},
onError: (e) {
_actionStreams.add(LogNotification(e.toString()));
},
);
}
void _addDevices(List<BleDevice> dev) {
final newDevices = dev.where((device) => !devices.contains(device)).toList();
devices.addAll(newDevices);
for (final device in newDevices) {
_connect(device).then((_) {});
}
hasDevices.value = devices.isNotEmpty;
if (devices.isNotEmpty && !androidNotificationsSetup && !kIsWeb && Platform.isAndroid) {
androidNotificationsSetup = true;
actionHandler.init(null);
NotificationRequirement.setup().catchError((e) {
_actionStreams.add(LogNotification(e.toString()));
});
}
}
Future<void> _connect(BleDevice bleDevice) async {
try {
await bleDevice.connect();
final actionSubscription = bleDevice.actionStream.listen((data) {
_actionStreams.add(data);
});
_streamSubscriptions[bleDevice] = actionSubscription;
final connectionStateSubscription = bleDevice.device.connectionState.listen((state) async {
_connectionStreams.add(bleDevice);
});
_connectionSubscriptions[bleDevice] = connectionStateSubscription;
} catch (e, backtrace) {
if (e is FlutterBluePlusException && e.code == FbpErrorCode.connectionCanceled.index) {
// ignore connections canceled by the user
} else {
_actionStreams.add(LogNotification(e.toString()));
if (kDebugMode) {
print(e);
print("backtrace: $backtrace");
}
}
}
}
void reset() {
FlutterBluePlus.stopScan();
for (var device in devices) {
device.device.disconnect();
}
devices.clear();
}
}

View File

@@ -1,93 +0,0 @@
import 'dart:async';
import 'dart:io';
import 'package:flutter/foundation.dart';
import 'package:flutter_blue_plus/flutter_blue_plus.dart';
import 'package:swift_control/utils/ble.dart';
import 'package:swift_control/utils/crypto/local_key_provider.dart';
import 'package:swift_control/utils/devices/zwift_click.dart';
import 'package:swift_control/utils/devices/zwift_play.dart';
import 'package:swift_control/utils/devices/zwift_ride.dart';
import '../crypto/zap_crypto.dart';
import '../messages/notification.dart';
abstract class BleDevice {
final ScanResult scanResult;
final zapEncryption = ZapCrypto(LocalKeyProvider());
bool supportsEncryption = true;
BleDevice(this.scanResult);
static BleDevice? fromScanResult(ScanResult scanResult) {
if (scanResult.device.platformName == 'Zwift Ride') {
return ZwiftRide(scanResult);
}
if (kIsWeb) {
// manufacturer data is not available on web
if (scanResult.device.platformName == 'Zwift Play') {
return ZwiftPlay(scanResult);
} else if (scanResult.device.platformName == 'Zwift Click') {
return ZwiftClick(scanResult);
}
}
final manufacturerData = scanResult.advertisementData.manufacturerData;
final data = manufacturerData[Constants.ZWIFT_MANUFACTURER_ID];
if (data == null || data.isEmpty) {
return null;
}
final type = DeviceType.fromManufacturerData(data.first);
return switch (type) {
DeviceType.click => ZwiftClick(scanResult),
DeviceType.playRight => ZwiftPlay(scanResult),
DeviceType.playLeft => ZwiftPlay(scanResult),
_ => null,
};
}
@override
bool operator ==(Object other) =>
identical(this, other) ||
other is BleDevice && runtimeType == other.runtimeType && scanResult == other.scanResult;
@override
int get hashCode => scanResult.hashCode;
@override
String toString() {
return runtimeType.toString();
}
BluetoothDevice get device => scanResult.device;
final StreamController<BaseNotification> actionStreamInternal = StreamController<BaseNotification>.broadcast();
Stream<BaseNotification> get actionStream => actionStreamInternal.stream;
Future<void> connect() async {
await device.connect(autoConnect: false).timeout(const Duration(seconds: 3));
var filteredStateStream = device.connectionState.where((s) => s == BluetoothConnectionState.connected);
// Start listening now, before invokeMethod, to ensure we don't miss the response
Future<BluetoothConnectionState> futureState = filteredStateStream.first;
// wait for connection
await futureState.timeout(
const Duration(seconds: 10),
onTimeout: () {
throw TimeoutException('Failed to connect in time.');
},
);
if (!kIsWeb && Platform.isAndroid) {
await device.requestMtu(256);
}
final services = await device.discoverServices();
if (device.isConnected) {
await handleServices(services);
}
}
Future<void> handleServices(List<BluetoothService> services);
}

View File

@@ -1,156 +0,0 @@
import 'dart:io';
import 'package:dartx/dartx.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter_blue_plus/flutter_blue_plus.dart';
import 'package:swift_control/main.dart';
import 'package:swift_control/utils/devices/ble_device.dart';
import 'package:swift_control/utils/messages/notification.dart';
import '../ble.dart';
import '../crypto/encryption_utils.dart';
import '../messages/click_notification.dart';
class ZwiftClick extends BleDevice {
ZwiftClick(super.scanResult);
List<int> get startCommand => Constants.RIDE_ON + Constants.RESPONSE_START_CLICK;
Guid get customServiceId => BleUuid.ZWIFT_CUSTOM_SERVICE_UUID;
@override
Future<void> handleServices(List<BluetoothService> services) async {
final customService = services.firstOrNullWhere((service) => service.uuid == customServiceId);
if (customService == null) {
throw Exception('Custom service not found');
}
final asyncCharacteristic = customService.characteristics.firstOrNullWhere(
(characteristic) => characteristic.uuid == BleUuid.ZWIFT_ASYNC_CHARACTERISTIC_UUID,
);
final syncTxCharacteristic = customService.characteristics.firstOrNullWhere(
(characteristic) => characteristic.uuid == BleUuid.ZWIFT_SYNC_TX_CHARACTERISTIC_UUID,
);
final syncRxCharacteristic = customService.characteristics.firstOrNullWhere(
(characteristic) => characteristic.uuid == BleUuid.ZWIFT_SYNC_RX_CHARACTERISTIC_UUID,
);
if (asyncCharacteristic == null || syncTxCharacteristic == null || syncRxCharacteristic == null) {
throw Exception('Characteristics not found');
}
if (!asyncCharacteristic.isNotifying) {
await asyncCharacteristic.setNotifyValue(true);
}
final asyncSubscription = asyncCharacteristic.lastValueStream.listen((onData) {
_processCharacteristic('async', Uint8List.fromList(onData));
});
device.cancelWhenDisconnected(asyncSubscription);
if (!syncTxCharacteristic.isNotifying) {
await syncTxCharacteristic.setNotifyValue(true, forceIndications: !kIsWeb && Platform.isAndroid);
}
final syncSubscription = syncTxCharacteristic.lastValueStream.listen((onData) {
_processCharacteristic('sync', Uint8List.fromList(onData));
});
device.cancelWhenDisconnected(syncSubscription);
await _setupHandshake(syncRxCharacteristic);
}
Future<void> _setupHandshake(BluetoothCharacteristic syncRxCharacteristic) async {
if (supportsEncryption) {
await syncRxCharacteristic.write([
...Constants.RIDE_ON,
...Constants.REQUEST_START,
...zapEncryption.localKeyProvider.getPublicKeyBytes(),
], withoutResponse: true);
} else {
await syncRxCharacteristic.write(Constants.RIDE_ON, withoutResponse: true);
}
}
void _processCharacteristic(String tag, Uint8List bytes) {
if (kDebugMode && false) {
print('Received $tag: ${bytes.map((e) => e.toRadixString(16).padLeft(2, '0')).join(' ')}');
print('Received $tag: ${String.fromCharCodes(bytes)}');
}
if (bytes.isEmpty) {
return;
}
try {
if (bytes.startsWith(startCommand)) {
_processDevicePublicKeyResponse(bytes);
} else if (bytes.startsWith(Constants.RIDE_ON)) {
//print("Empty RideOn response - unencrypted mode");
} else if (!supportsEncryption || (bytes.length > Int32List.bytesPerElement + EncryptionUtils.MAC_LENGTH)) {
_processData(bytes);
} else if (bytes[0] == Constants.DISCONNECT_MESSAGE_TYPE) {
//print("Disconnect message");
} else {
//print("Unprocessed - Data Type: ${bytes.map((e) => e.toRadixString(16).padLeft(2, '0')).join(' ')}");
}
} catch (e, stackTrace) {
print("Error processing data: $e");
print("Stack Trace: $stackTrace");
actionStreamInternal.add(LogNotification(e.toString()));
}
}
ClickNotification? _lastClickNotification;
void _processData(Uint8List bytes) {
int type;
Uint8List message;
if (supportsEncryption) {
final counter = bytes.sublist(0, 4); // Int.SIZE_BYTES is 4
final payload = bytes.sublist(4);
final data = zapEncryption.decrypt(counter, payload);
type = data[0];
message = data.sublist(1);
} else {
type = bytes[0];
message = bytes.sublist(1);
}
switch (type) {
case Constants.EMPTY_MESSAGE_TYPE:
//print("Empty Message"); // expected when nothing happening
break;
case Constants.BATTERY_LEVEL_TYPE:
//print("Battery level update: $message");
break;
case Constants.CLICK_NOTIFICATION_MESSAGE_TYPE:
case Constants.PLAY_NOTIFICATION_MESSAGE_TYPE:
case Constants.RIDE_NOTIFICATION_MESSAGE_TYPE: // untested
processClickNotification(message);
break;
}
}
void _processDevicePublicKeyResponse(Uint8List bytes) {
final devicePublicKeyBytes = bytes.sublist(Constants.RIDE_ON.length + Constants.RESPONSE_START_CLICK.length);
zapEncryption.initialise(devicePublicKeyBytes);
if (kDebugMode) {
print("Device Public Key - ${devicePublicKeyBytes.map((e) => e.toRadixString(16).padLeft(2, '0')).join(' ')}");
}
}
void processClickNotification(Uint8List message) {
final ClickNotification clickNotification = ClickNotification(message);
if (_lastClickNotification == null || _lastClickNotification != clickNotification) {
_lastClickNotification = clickNotification;
actionStreamInternal.add(clickNotification);
if (clickNotification.buttonUp) {
actionHandler.increaseGear();
} else if (clickNotification.buttonDown) {
actionHandler.decreaseGear();
}
}
}
}

View File

@@ -1,30 +0,0 @@
import 'package:flutter/foundation.dart';
import 'package:swift_control/utils/devices/zwift_click.dart';
import 'package:swift_control/utils/messages/controller_notification.dart';
import '../../main.dart';
import '../ble.dart';
class ZwiftPlay extends ZwiftClick {
ZwiftPlay(super.scanResult);
ControllerNotification? _lastControllerNotification;
@override
List<int> get startCommand => Constants.RIDE_ON + Constants.RESPONSE_START_PLAY;
@override
void processClickNotification(Uint8List message) {
final ControllerNotification clickNotification = ControllerNotification(message);
if (_lastControllerNotification == null || _lastControllerNotification != clickNotification) {
_lastControllerNotification = clickNotification;
actionStreamInternal.add(clickNotification);
if (clickNotification.rightPad && clickNotification.analogLR.abs() == 100) {
actionHandler.increaseGear();
} else if (!clickNotification.rightPad && clickNotification.analogLR.abs() == 100) {
actionHandler.decreaseGear();
}
}
}
}

Some files were not shown because too many files have changed in this diff Show More