Skip to content

[WOOMOB-547] Add Heuristics for differentiating between barcode scanner and HW keyboard #14162

New issue

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

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

Already on GitHub? Sign in to your account

Merged

Conversation

malinajirka
Copy link
Contributor

@malinajirka malinajirka commented Jun 9, 2025

WOOMOB-373

Description

This PR introduces the BarcodeInputDetector class that helps differentiate between input from a hardware keyboard and input from a barcode scanner.

How It Works:
The detector differentiates between manual keyboard typing and automatic barcode scanner input by analyzing timing patterns:

  • Barcode scanners typically input characters very rapidly in sequence.
  • The detector tracks time between keystrokes to identify scanner patterns
  • When a barcode is detected, it's passed to the provided callback function

Time-based detection:
Uses two timing thresholds

  • MAX_SCANNER_INTER_CHAR_DELAY_MS (100ms): Maximum delay between characters from scanner (my scanner inputs characters between 5-60ms). If two keystrokes are further apart than 100ms it's considered as human input and ignored.
  • MAX_SCANNER_TOTAL_SCAN_TIMEOUT_MS (1500ms): Maximum total time for a complete scan (I set it to 1500 as a reasonably sized barcode won't be longer than 25 characters if we assume average character inter-delay 60ms - my barcode scanner has average delay around 20ms so this feels like a huge enough buffer). If the timeout elapses, the input is validated and callback is invoked (this is handling for scanners that do not pass end-of-line character.

Character validation: Only allows alphanumeric and common special characters
Minimum length: Rejects potential barcodes shorter than 4 characters
Auto-completion: Scan completes on Enter key or after timeout
Reset mechanism: Automatically resets state when human typing is detected

Testing information

  • Try scanning barcodes and verify items are added to the cart.
  • Try typing on a hardware keyboard and verify items are not added to the cart unless you type at least 4 characters extremely fast.

The tests that have been performed

  • I've tested this with with a hardware scanner - I tried disabling the end-of-line suffix to verify items are added to the cart even when the end-of-line character is not provided.

Images/gif

No user-facing changes.

  • I have considered if this change warrants release notes and have added them to RELEASE-NOTES.txt if necessary. Use the "[Internal]" label for non-user-facing changes.

cc @joshheald

@malinajirka malinajirka requested a review from Copilot June 9, 2025 15:27
Copy link
Contributor

@Copilot Copilot AI left a comment

Choose a reason for hiding this comment

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

Pull Request Overview

This PR introduces a dedicated BarcodeInputDetector to distinguish fast scanner input from manual keyboard entry and integrates it into a Compose modifier, accompanied by new unit tests.

  • Extract barcode collection and timing logic into BarcodeInputDetector with configurable timeouts and clear/reset behavior.
  • Update listenForBarcodes modifier to use the detector, handle lifecycle cleanup, and run timeouts via CoroutineScope.
  • Add comprehensive tests covering fast vs. slow input, invalid chars, timeouts, and consecutive scans.

Reviewed Changes

Copilot reviewed 2 out of 2 changed files in this pull request and generated 1 comment.

File Description
WooCommerce/src/main/kotlin/com/woocommerce/android/ui/woopos/common/composeui/modifier/BarcodeScannerModifier.kt Refactored modifier to use BarcodeInputDetector with coroutine-based timeouts and added disposal logic
WooCommerce/src/test/kotlin/com/woocommerce/android/ui/woopos/common/composeui/modifier/BarcodeInputDetectorTest.kt Added unit tests simulating scanner vs. human typing, invalid inputs, and timeout behaviors

@wpmobilebot
Copy link
Collaborator

wpmobilebot commented Jun 9, 2025

📲 You can test the changes from this Pull Request in WooCommerce-Wear Android by scanning the QR code below to install the corresponding build.
App Name WooCommerce-Wear Android
Platform⌚️ Wear OS
FlavorJalapeno
Build TypeDebug
Commit94bf35d
Direct Downloadwoocommerce-wear-prototype-build-pr14162-94bf35d.apk

@malinajirka malinajirka requested a review from kidinov June 9, 2025 15:38
@malinajirka malinajirka added this to the 22.6 milestone Jun 9, 2025
@malinajirka malinajirka marked this pull request as ready for review June 9, 2025 15:41
@wpmobilebot
Copy link
Collaborator

wpmobilebot commented Jun 9, 2025

📲 You can test the changes from this Pull Request in WooCommerce Android by scanning the QR code below to install the corresponding build.

App Name WooCommerce Android
Platform📱 Mobile
FlavorJalapeno
Build TypeDebug
Commit94bf35d
Direct Downloadwoocommerce-prototype-build-pr14162-94bf35d.apk

@codecov-commenter
Copy link

codecov-commenter commented Jun 9, 2025

Codecov Report

Attention: Patch coverage is 81.96721% with 11 lines in your changes missing coverage. Please review.

Project coverage is 37.90%. Comparing base (d193375) to head (94bf35d).
Report is 122 commits behind head on trunk.

Files with missing lines Patch % Lines
...ommon/composeui/modifier/BarcodeScannerModifier.kt 81.96% 9 Missing and 2 partials ⚠️
Additional details and impacted files
@@             Coverage Diff              @@
##              trunk   #14162      +/-   ##
============================================
+ Coverage     37.87%   37.90%   +0.02%     
  Complexity     8959     8959              
============================================
  Files          1956     1956              
  Lines        109225   109274      +49     
  Branches      14305    14313       +8     
============================================
+ Hits          41367    41417      +50     
+ Misses        64085    64082       -3     
- Partials       3773     3775       +2     

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@joshheald
Copy link
Contributor

Thanks for the ping @malinajirka

The heuristics as you describe them look good. My only question is why 4 characters?

Minimum length: Rejects potential barcodes shorter than 4 characters

UPC-E is the shortest of the common symbologies we're looking to support, and that uses 6 characters. Is there some other use case I'm missing for shorter codes?

That said, with custom barcodes in QR codes, I guess someone could have shorter codes. I think it comes down to: what's going to give us the best accuracy in scanning, without compromising common barcode format support?

companion object {
@Suppress("SpellCheckingInspection")
const val ALLOWED_BARCODE_CHARS =
"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-._~:/?#[]@!$&'()*+,;="
Copy link
Contributor

Choose a reason for hiding this comment

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

What's the source for this character set?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Good question, I realized it doesn't include all the characters supported by some of the allowed symbologies so I removed this check completely 3e5c772 - for example Code 39 Ext. or Code 128 support all ASCII characters, QR codes support even more.

@malinajirka
Copy link
Contributor Author

Thanks for looking into this @joshheald !

The heuristics as you describe them look good. My only question is why 4 characters?
Minimum length: Rejects potential barcodes shorter than 4 characters
UPC-E is the shortest of the common symbologies we're looking to support, and that uses 6 characters. Is there some other use case I'm missing for shorter codes?
That said, with custom barcodes in QR codes, I guess someone could have shorter codes. I think it comes down to: what's going to give us the best accuracy in scanning, without compromising common barcode format support?

As you mentioned for example QR codes support codes of any length, however, I don't think we can come up with a heuristic which would reliable allow such scans. I tried to find a reasonably but as short as possible length to give us decent accuracy. Wdyt?

@kidinov kidinov self-assigned this Jun 10, 2025
private val coroutineScope: CoroutineScope,
private val currentTimeProvider: CurrentTimeProvider,
) {
companion object {
Copy link
Contributor

Choose a reason for hiding this comment

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

np: probably should be private

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Updated in db700f6

@kidinov
Copy link
Contributor

kidinov commented Jun 10, 2025

@malinajirka 👋

Looks good, but I don't understand what specifically it gives as? That if a new line char is not coming, we'll still submit it as a barcode? The search in focus will still put scanned data in it, correct?

@kidinov kidinov self-requested a review June 10, 2025 14:14
Copy link
Contributor

@kidinov kidinov left a comment

Choose a reason for hiding this comment

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

The code looks good but I am 100% understand what it is for 😀. I asked it in the comment

@malinajirka
Copy link
Contributor Author

Thanks for the review!

Looks good, but I don't understand what specifically it gives as? That if a new line char is not coming, we'll still submit it as a barcode? The search in focus will still put scanned data in it, correct?

It gives us two things:

  1. support for scanners that do not put the end-of-line character after the scan,
  2. typing on the keyboard and pressing enter won't be detected as scan.

@malinajirka malinajirka enabled auto-merge June 11, 2025 06:20
@malinajirka malinajirka merged commit 0e152cd into trunk Jun 11, 2025
17 checks passed
@malinajirka malinajirka deleted the issue/woomob-547-woo-posbarcodes-add-scanning-heuristics branch June 11, 2025 07:20
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

5 participants