TheRelentlessDev

All things tech with a sprinkle of make

NAVIGATION - SEARCH

Handheld Barcode Scanner with .NET (C#)

Background

The requirement is to integrate a Honeywell 1450G corded handheld scanner with a piece of .NET software. The scanner will be used for inventory and tracking via QR Codes. The barcode will be generated by another piece of software, printed onto a label and placed on a piece of hardware. The custom application needs to scan the QR code and decode it, send the data to the custom application and then determine if a new entry needs to be added to the database. Alternatively an existing entry needs to be called up for potential edits.

The main purpose of this article is to highlight the steps required for getting the scanner to communicate with the C# application running on Windows 10 Professional.

Hardware connection and configuration

The first step is to connect the scanner via the USB cable to the computer. No external drivers are required. Once the hardware has been detected and Windows has completed setting up the require drivers, there will be two devices present visible in Device Manager. The scanner can be used as a Keyboard input device or as an HID device. For keyboard input you can set focus to any edit box or something like notepad, scan a code and the data will be shown in the text window. The problem using the scanner in this way is that keyboard events with message prefixes and postfixes will have to be intercepted and parsed. This is the more popular method of using barcode scanners.

I however would like to use the scanner in HID mode. To do this you need to scan a couple of barcodes in the manual (provided in point 2 of the references). Go to page 2 – 4 and scan the USB HID barcode.

This will disable the keyboard mode (in Device Manager the driver installed under keyboards will be removed) and put the scanner in USB HID mode. You should see the Device Driver installation dialog pop up and start installing drivers again. Once complete you should only see a POS (Point of Sale) device listed in Device Manager. Next we need to clear all prefixes and suffixes. On page 5 – 2 and page 5 – 3 scan the ‘Clear all Prefixes’ and the ‘Clear all Suffixes’ codes.

In the next step we will look at how to communicate with the scanner using C#

#region License
/* Copyright 2012-2013 James F. Bellinger <http://www.zer7.com/software/hidsharp>

   Permission to use, copy, modify, and/or distribute this software for any
   purpose with or without fee is hereby granted, provided that the above
   copyright notice and this permission notice appear in all copies.

   THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
   WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
   MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
   ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
   WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
   ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
   OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */
#endregion


using System;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading;

namespace HidSharp.Test
{
    class Program
    {
        static void Main(string[] args)
        {
            HidDeviceLoader loader = new HidDeviceLoader();
            Thread.Sleep(2000); // Give a bit of time so our timing below is more valid as a benchmark.

            var stopwatch = new Stopwatch();
            stopwatch.Start();
            var deviceList = loader.GetDevices().ToArray();
            stopwatch.Stop();
            long deviceListTotalTime = stopwatch.ElapsedMilliseconds;

            Console.WriteLine("Complete device list (took {0} ms to get {1} devices):",
                              deviceListTotalTime, deviceList.Length);
            foreach (HidDevice dev in deviceList)
            {
                Console.WriteLine(dev);
            }
            Console.WriteLine();

            Console.WriteLine("Opening HID class device...");


            var dtest_evice = loader.GetDevices(3118);
            var device = loader.GetDevices(3118).FirstOrDefault(d => d.ProductName == "HID POS");
            if (device == null) { Console.WriteLine("Failed to open device."); Environment.Exit(1); }

            Console.Write(@"
				Max Lengths:
				  Input:   {0}
				  Output:  {1}
				  Feature: {2}

				The operating system name for this device is:
				  {3}

				"
				, device.MaxInputReportLength
				, device.MaxOutputReportLength
				, device.MaxFeatureReportLength
				, device.DevicePath
				);

            HidStream stream;
            if (!device.TryOpen(out stream)) { Console.WriteLine("Failed to open device."); Environment.Exit(2); }
            StringBuilder sb = new StringBuilder();
            using (stream)
            {
                int n = 0;
                while (true)
                {
                    var bytes = new byte[device.MaxInputReportLength];
                    int count;

                    try
                    {
                        count = stream.Read(bytes, 0, bytes.Length);
                    }
                    catch (TimeoutException)
                    {
                        Console.WriteLine("Read timed out.");
                        continue;
                    }

                    if (count > 0)
                    {
                        var decoded = Encoding.UTF8.GetString(bytes);
                        if (decoded.IndexOf("\u0002\u0003]Q1\n\r\n\0") >= 0)
                        {
                            Console.WriteLine(sb.ToString());
                            sb.Length = 0;
                        }
                        else
                        {
                            sb.Append(decoded.Replace("\u00028]Q1", "").Replace("s\0\u0001", " "));
                        }
                        Console.WriteLine();
                        if (++n == 100)
                        {
                            break;
                        }
                    }
                }
            }

            Console.WriteLine("Press a key to exit...");
            Console.ReadKey();
        }
    }
}

 

Connecting with C#

First we need to download an HID library that will allow us to communicate with the POS device. Go to http://www.zer7.com/software/hidsharp and download the latest HIDSharp library. Unzip the library and open the HidSharp.sln in Visual Studio. Set the HidSharp.Test project as the startup and modify the Program.cs file as follows:

Build and run the application. Scan a Barcode/QR Code. You should see the decoded content in the console window.

References

  1. HIDSharp. 2016. HIDSharp. [ONLINE] Available at: http://www.zer7.com/software/hidsharp. [Accessed 03 October 2016].
  2. HONEYWELL VOYAGER 1450G SERIES USER MANUAL Pdf Download.. 2016. HONEYWELL VOYAGER 1450G SERIES USER MANUAL Pdf Download.. [ONLINE] Available at:http://www.manualslib.com/manual/896845/Honeywell-Voyager-1450g-Series.html. [Accessed 03 October 2016].

Add comment