Skip to content
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

Add support for detecting and turning on/off flash light #241

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 16 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,7 @@ This is a cross-platform Javascript library to integrate QR code, bar codes & a

Supports:
- Querying camera on the device (with user permissions)
- Turning on/off flash light if device supports that
- Rendering live camera feed, with easy to use user interface for scanning
- Supports scanning a different kind of QR codes, bar codes and other formats
- Supports selecting image files from the device for scanning codes
Expand Down Expand Up @@ -144,7 +145,7 @@ html5QrcodeScanner.render(onScanSuccess, onScanFailure);
### Pro Mode - if you want to implement your own user interface
You can use `Html5Qrcode` class to set up your QR code scanner (with your own user interface) and allow users to scan QR codes using the camera or by choosing an image file in the file system or native cameras in smartphones.

You can use the following APIs to `fetch camera`, `start` scanning and `stop` scanning.
You can use the following APIs to `fetch camera`, `start` scanning, `stop` scanning and `set flash` state.

#### For using inline QR Code scanning with Webcam or Smartphone camera

Expand Down Expand Up @@ -238,6 +239,20 @@ html5QrCode.stop().then((ignore) => {

> Note that the class is stateful and `stop()` should be called to properly tear down the video and camera objects safely after calling `start()` when the scan is over or the user intend to move on. `stop()` will stop the video feed on the viewfinder.

### Flash light support

To detect if camera supports flash light, call call `Html5Qrcode#hasFlash()` which returns a `Promise` with detected result.
```js
html5QrCode.hasFlash().then((hasFlash) => {
if (hasFlash) {
// Flash light is supported, turn it on
html5QrCode.setFlash(true);
}
});
```

> Not that camera must be already selected and started to be able to detect and turn on flash light.

#### For QR Code scanning using local files or inbuild camera on Smartphones
| Selector in Android | Selector in IOS|
|------|-------|
Expand Down
2 changes: 1 addition & 1 deletion dist/html5-qrcode.min.js

Large diffs are not rendered by default.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@
"@babel/core": "^7.11.4",
"@babel/plugin-proposal-class-properties": "^7.10.4",
"@babel/preset-env": "^7.11.0",
"@types/w3c-image-capture": "^1.0.3",
"babel-minify": "^0.5.1",
"chai": "^4.2.0",
"expose-loader": "^2.0.0",
Expand Down
31 changes: 31 additions & 0 deletions src/html5-qrcode-scanner.ts
Original file line number Diff line number Diff line change
Expand Up @@ -441,6 +441,13 @@ export class Html5QrcodeScanner {
cameraActionStopButton.disabled = true;
cameraActionContainer.appendChild(cameraActionStopButton);

const flashActionToggleButton = document.createElement("button");
flashActionToggleButton.innerText
= Html5QrcodeScannerStrings.toggleFlashOnText();
flashActionToggleButton.style.display = "none";
flashActionToggleButton.disabled = true;
cameraActionContainer.appendChild(flashActionToggleButton);

scpCameraScanRegion.appendChild(cameraActionContainer);

cameraActionStartButton.addEventListener("click", (_) => {
Expand All @@ -458,6 +465,12 @@ export class Html5QrcodeScanner {
cameraActionStopButton.style.display = "inline-block";
cameraActionStartButton.style.display = "none";
$this.setStatus(Html5QrcodeScannerStrings.scanningStatus());
$this.html5Qrcode!.hasFlash().then((hasFlash) => {
if (hasFlash) {
flashActionToggleButton.style.display = "inline-block";
flashActionToggleButton.disabled = false;
}
});
})
.catch((error) => {
$this.showHideScanTypeSwapLink(true);
Expand All @@ -481,6 +494,7 @@ export class Html5QrcodeScanner {
cameraActionStartButton.disabled = false;
cameraActionStopButton.style.display = "none";
cameraActionStartButton.style.display = "inline-block";
flashActionToggleButton.style.display = "none";
$this.setStatus(Html5QrcodeScannerStrings.idleStatus());
$this.insertCameraScanImageToScanRegion();
}).catch((error) => {
Expand All @@ -492,6 +506,23 @@ export class Html5QrcodeScanner {
error, Html5QrcodeScannerStatus.STATUS_WARNING);
});
});

flashActionToggleButton.addEventListener("click", (_) => {
if (!$this.html5Qrcode) {
throw "html5Qrcode not defined";
}
flashActionToggleButton.disabled = true;
$this.html5Qrcode.setFlash(!$this.html5Qrcode.isFlashOn()).then((_) => {
flashActionToggleButton.disabled = false;
if ($this.html5Qrcode && $this.html5Qrcode.isFlashOn()) {
flashActionToggleButton.innerText
= Html5QrcodeScannerStrings.toggleFlashOffText();
} else {
flashActionToggleButton.innerText
= Html5QrcodeScannerStrings.toggleFlashOnText();
}
});
});
}

private createSectionSwap() {
Expand Down
71 changes: 69 additions & 2 deletions src/html5-qrcode.ts
Original file line number Diff line number Diff line change
Expand Up @@ -237,6 +237,7 @@ export class Html5Qrcode {
private qrRegion: QrcodeRegionBounds | null = null;
private context: CanvasRenderingContext2D | null = null;
private lastScanImageFile: string | null = null;
private flashOn: boolean;
Copy link
Owner

Choose a reason for hiding this comment

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

nit, rename to isFlashOn for easier reading.

//#endregion

public isScanning: boolean;
Expand Down Expand Up @@ -285,7 +286,7 @@ export class Html5Qrcode {
this.localMediaStream;
this.shouldScan = true;
this.isScanning = false;

this.flashOn = false;
}

//#region start()
Expand Down Expand Up @@ -393,7 +394,14 @@ export class Html5Qrcode {
qrCodeErrorCallback!)
.then((_) => {
$this.isScanning = true;
resolve(/* Void */ null);
if (!$this.flashOn) {
resolve(/* Void */ null);
return;
}
// Turn on flash light if it was turned on before
$this.setFlash(true).then(() => {
resolve(/* Void */ null);
});
})
.catch(reject);
})
Expand Down Expand Up @@ -492,6 +500,7 @@ export class Html5Qrcode {

this.localMediaStream!.getVideoTracks().forEach((videoTrack) => {
this.localMediaStream!.removeTrack(videoTrack);
// This will also stop flash light
videoTrack.stop();
++tracksClosed;

Expand All @@ -502,6 +511,63 @@ export class Html5Qrcode {
});
}

/**
* Checks if current video track has flash light capability.
*
* This feature requires that camera is started.
*
* @returns Promise with detected flash capability result.
*/
public hasFlash(): Promise<boolean> {
if (!("ImageCapture" in window)) {
return Promise.resolve(false);
}

const track = this.videoElement?.srcObject ? (<MediaStream>this.videoElement.srcObject).getVideoTracks()[0] : null;
Copy link
Owner

Choose a reason for hiding this comment

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

nit, split into two lines?

Copy link
Owner

Choose a reason for hiding this comment

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

Comment 2: could this lead to null ptr exception if ...getVideoTracks() returns undefined or empty array? we should do a length check first.

if (!track) {
throw "Scan should be started to detect flash capability";
}

return new ImageCapture(track).getPhotoCapabilities()
.then((result) => {
return result.fillLightMode.includes("flash");
})
.catch((err) => {
this.logger.warn(err);
return false;
});
}

/**
* Checks if flash is turned on.
*
* @returns Current flash state.
*/
public isFlashOn(): boolean {
Copy link
Owner

Choose a reason for hiding this comment

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

why expose this state via a public method?

return this.flashOn;
}

/**
* Change flash state.
*
* @param on if true flash will be turned on otherwise turned off.
* @returns Promise that flash state has changed.
*/
public setFlash(on: boolean): Promise<void> {
Copy link
Owner

Choose a reason for hiding this comment

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

optional, rename to more readable shouldSetFlashOn or something more relevant.

return this.hasFlash().then((hasFlash) => {
if (!hasFlash) {
return Promise.reject("No flash available");
}

// At this point we already know that video element is not null and has track
return (<MediaStream>this.videoElement!.srcObject).getVideoTracks()[0].applyConstraints({
advanced: [{ torch: on }]
});
}).then(() => {
this.flashOn = on;
});
}

/**
* Scans an Image File for QR Code.
*
Expand Down Expand Up @@ -767,6 +833,7 @@ export class Html5Qrcode {
const tracks = stream.getVideoTracks();
for (const track of tracks) {
track.enabled = false;
// This will also stop flash light
Copy link
Owner

Choose a reason for hiding this comment

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

super nit, add a "." after the comment

Copy link
Owner

Choose a reason for hiding this comment

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

(ditto elsewhere)

track.stop();
stream.removeTrack(track);
}
Expand Down
8 changes: 8 additions & 0 deletions src/strings.ts
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,14 @@ export class Html5QrcodeScannerStrings {
return "Start Scanning";
}

public static toggleFlashOnText(): string {
return "Turn flash on";
}

public static toggleFlashOffText(): string {
return "Turn flash off";
}

/**
* Text to show when camera scan is selected.
*
Expand Down
2 changes: 1 addition & 1 deletion tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
"sourceMap": true,
"moduleResolution": "classic",
"lib": [
"es7",
"es2018",
Copy link
Author

Choose a reason for hiding this comment

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

this was already needed for:

.finally(() => {

"dom"
],

Expand Down