Raspberry Pi ~ Linux Barcode Scanner Part Deux

Here’s an evolved php script to detect serial port usb scanners and grab the input from them. Simply identify the scanner using ls -l /dev/serial/by-id and change the name of the deviceID variable to your device. Be sure you set your scanner to virtual serial port and don’t forget to run the script as root.

<?php
register_shutdown_function('gnight');
$deviceID = "usb-SM_SM-2D_PRODUCT_USB_UART_APP";
$deviceFile = GetDevice($deviceID);
$fpath = "/dev/{$deviceFile}";
if(is_readable($fpath))    {
    $fhandle = fopen($fpath, 'r' ); # Open device for Read access
}
$inC = 0;
$buffer = '';
while (ContinueLoop())    {
    # Read data from device
    $tagid = fgetc($fhandle);
    if(ord($tagid)>31)  {
        $buffer .= $tagid;
    }
    else    {
        echo "$buffer\n";
        /* 
        * Call other scripts and pass data.
        */
        $buffer = '';
    }      
}

function gnight()   {
    global $handle, $fpath;
    
    if(is_object($handle)) {
        echo "Closing {$fpath}\n";
        fclose($handle);
    }
    else {
        echo "No file handle for {$fpath}..\n";
    }
    echo "Shutdown complete\n";
}

function ContinueLoop() {
    //Check database or file for interupt here. Return false to exit.
    global $fpath;
    if(!is_readable($fpath))    {
        echo "Lost scanner {$fpath}..\n";
        return false;
    }
    return true;
}

function GetDevice($devID)    {
    $res = shell_exec("ls -l /dev/serial/by-id");
    echo "Searching for device {$devID}\n";
    $res = explode(PHP_EOL,$res);
    $retVal = '';
    foreach($res as $rKey=>$rVal)   {
        if(strlen(trim($rVal)) == 0 || stripos($rVal,"total") !== false || strpos($rVal,"->") == false)    {continue;}
        if(stristr($rVal,$devID)!==false)   {
            $ptsAr = explode("->",$rVal);
            if(is_array($ptsAr) && count($ptsAr) == 2)   {
                $retVal = trim(str_replace([' ','.','/'],'',$ptsAr[1]));
            }
        }
    }
    echo "Device detected {$retVal}\n";
    return $retVal;
}

Author: Joel Caton

Business Consultant and Web Developer from Meridian, MS

1 thought on “Raspberry Pi ~ Linux Barcode Scanner Part Deux”

  1. І am гeally glad to glance at thiѕ web site posts which inclᥙdeѕ lotѕ
    of ᥙseful infoгmation, thɑnks foг providing tһеse
    іnformation.

Leave a Reply

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