How to Use Quagga Js in Odoo 16

How to Use Quagga Js in Odoo 16

7 minutes, 24 seconds Read

QuaggaJS is a JavaScript-based barcode scanner that offers real-time localization and decoding functionality for a wide range of barcode types, including EAN, CODE 128, CODE 39, EAN 8, UPC-A, UPC-C, I2of5, 2of5, CODE 93, and CODABAR. This library utilizes getUserMedia to directly access the camera stream, enabling efficient barcode scanning.

Browser Support

QuaggaJS utilizes a variety of modern Web APIs, although not all web browsers support these APIs at present. The library operates in two distinct modes: the first involves analyzing static images, while the second involves using a camera to decode images from a live stream. The latter mode specifically relies on the MediaDevices API, which is necessary for accessing and utilizing the camera for real-time decoding.
It is possible to monitor the compatibility of the utilized Web APIs for different modes:
1. Static Images
The following APIs need to be implemented in your browser:
* web workers
* canvas
* typed arrays
* blob URLs
* blob builder
2. Live Stream
In addition to the APIs mentioned above in the Static Images,
* MediaDevices

Installing      

QuaggaJS offers multiple installation options. You can install it via npm or bower package managers, or simply include it by using the script tag in your HTML file.

Installing using NPM:

> npm install quagga
And then import it as dependency in your project:
import Quagga from ‘quagga’;
const Quagga = require(‘quagga’).default;
QuaggaJS currently provides its complete range of functionality exclusively within the browser environment. Only file-based decoding is supported when using QuaggaJS in a Node.js environment, and certain features may be limited compared to the browser version.
Installing using Bower:
> bower install quagga
You can easily integrate the library by including the dist/quagga.min.js file in your project. The script exposes the Quagga library on the global namespace, enabling seamless usage.

Building

You can build the library yourself by simply cloning the repo and typing:
> npm install
> npm run build
The provided npm script facilitates the construction of Quagga.js by generating both an unoptimized version, quagga.js, and a minified version, quagga.min.js, which are then stored in the dist folder. Furthermore, a source map named quagga.map is included alongside these files. It is important to note that the source map is solely applicable to the non-uglified version, quagga.js, as the minified version undergoes modifications after compression, resulting in misalignment with the map file.
The contents of the dist folder contain code specifically designed for browser environments, relying on the Document Object Model (DOM). As a result, this code is incompatible with Node.js due to the absence of the DOM. To enable usage within Node.js, the build command generates an additional quagga.js file in the lib folder, which is tailored for Node.js compatibility. This version of the file can be utilized in Node.js environments successfully.
Here is an example of how to use QuaggaJS for searching the product using the barcode in the odoo website:
publicWidget.registry.WebsiteSaleBarcode = publicWidget.Widget.extend({
	selector: '.oe_website_sale',
	disabledInEditableMode: false,
	events: {
    	'click .o_wsale_apply_barcode ': 'load_quagga',
	},
    	load_quagga: function (ev) {
         	if ($('#barcode_id').length > 0 && 
            navigator.mediaDevices && typeof  navigator.mediaDevices.getUserMedia ===          'function')
{
            	Quagga.init({
            	inputStream : {
                	name : "Live",
                	type : "LiveStream",
                	constraints: {
                    	video: {
                        	facingMode: {
                          	exact: "environment"
                        	}
                      	}
                       	},
                	numOfWorkers : navigator.hardwareConcurrency,
                	target : document.querySelector('#barcode_id')
            	},
            	decoder: {
               	readers : ['code_128_reader']
            	}
            	},function(err){
                	if(err){
                	console.log(err);
                	return
                	}
                	Quagga.start();
            	});
            	var last_result=[];
            	var self = this;
            	Quagga.onDetected(function(result){
                	var last_code = result.codeResult.code;
                	last_result.push(last_code);
                	last_result=[];
                	Quagga.stop();
                	ajax.jsonRpc('/shop/barcodeproduct','call', {
                        	'last_code':last_code
                        	}).then(function(result){
                            	if(result== false){
                                	alert('Barcode is not detected.')
                                  	}
                            	else {
                             	window.location.href=result['url'];
                             	}
                        	});
            	});
         	}
    	},
});
});
 Quagga.init(config, callback)
This method initializes the Quagga library by providing a configuration object (config), and it triggers the callback function (err) when the bootstrapping phase is completed. If real-time detection is configured during initialization, the library also requests camera access. If an error occurs, the err parameter is populated with relevant information, such as when the inputStream.type is set to LiveStream, but the browser lacks support for this API or when the user denies camera permission.
If no target is specified, QuaggaJS will search for an element that matches the CSS selector #interactive.viewport, which is used for backward compatibility. The target parameter can be either a string representing a CSS selector that matches a DOM node or the DOM node itself.
Quagga.start()
Upon initializing the library, invoking the start() method initiates the video-stream, allowing for image localization and decoding to commence.
Quagga.stop()
Once the decoder is in an active state, invoking the stop() method halts any further image processing. Moreover, if a camera-stream was requested during initialization, this action also disengages the camera connection.
Quagga.onProcessed(callback)
This method allows you to register a callback function (callback(data)) that will be invoked for each frame after the processing is completed. The data object passed to the callback contains comprehensive information regarding the outcome of the operation, including success or failure details. The specific output provided in the data object may differ based on the success or failure of the detection and/or decoding process.
Quagga.onDetected(callback)
By registering a callback function, callback(data), you can receive notifications whenever a barcode pattern is successfully located and decoded. The data object passed to the callback includes details about the decoding process, including the detected code. You can retrieve the decoded code by accessing data.codeResult.code.
Quagga.decodeSingle(config, callback)
Unlike the aforementioned methods that utilize getUserMedia and work with video streams, this particular method functions with a single image. It does not require getUserMedia. The provided callback function is the same as the one used in onDetected and receives the result data object as its parameter.
Quagga.offProcessed(handler)
If the onProcessed event is no longer necessary, you can use offProcessed to remove the provided handler from the event queue.
Quagga.offDetected(handler)
If the onDetected event is no longer applicable, you can utilize offDetected to eliminate the specified handler from the event queue.

Configuration

1. numOfWorkers

QuaggaJS inherently supports web workers and operates with a default configuration of 4 workers. It is recommended that the number of workers aligns with the available cores in the targeted devices. If you are uncertain about the exact number or if you have a wide range of devices, you have two options: either utilize navigator.hardwareConcurrency or employ the core-estimator feature.

2. locate

The locate property determines the status of this feature, allowing you to enable (default) or disable it.

3. inputStream

The inputStream property specifies the sources of images/videos used within QuaggaJS.  
1. The “type” property in the configuration can be assigned one of three values: “ImageStream,” “VideoStream,” or “LiveStream” (with “LiveStream” being the default option).
2. The “constraint” key in the configuration specifies the physical dimensions of the input image, along with other properties such as “facingMode” which determines the source of the user’s camera when multiple devices are available. If needed, the “deviceId” property can be set to allow the user to select a specific camera. This can be accomplished effortlessly using the MediaDevices.enumerateDevices() method.
3. The “area” property in the configuration allows for restricting the decoding area of the image. The values for the area are specified in percentages, similar to the CSS style property when using “position: absolute.” This feature is particularly useful when the “locate” property is set to false, as it enables the definition of a specific rectangle for the user within which decoding should occur.
4. The “singleChannel” property is primarily used for debugging purposes when investigating unexpected decoder behavior. When this property is set to true, the decoder reads the red color-channel of the input image instead of calculating the gray-scale values from the RGB channels. This feature is particularly useful when used in conjunction with the ResultCollector, as it allows for the saving of gray-scale representations of incorrectly identified images.

4. frequency

The scanFrequency property at the top level determines the scanning frequency of the video stream. It is an optional property that specifies the maximum number of scans per second. This is particularly helpful in scenarios where the scan session is expected to be lengthy and resource usage, such as CPU power, needs to be managed efficiently.

5. decoder

In its default configuration, QuaggaJS typically operates in a two-stage manner (when locate is set to true). First, it locates the barcode, and then it initiates the decoding process. Decoding involves transforming the bars into their actual meaning. The majority of the configuration options within the decoder are primarily intended for debugging and visualization purposes.
One of the key properties to note is “readers,” which accepts an array of barcode types to be decoded during the session. You can specify the desired barcode types using the following values:
* code_128_reader (default)
* ean_reader
* ean_8_reader
* code_39_reader
* code_39_vin_reader
* codabar_reader
* upc_reader
* upc_e_reader
* i2of5_reader
* 2of5_reader
* code_93_reader

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *